package com.zbkj.crmeb.merchant.api.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.annotation.Resource;

import cn.hutool.core.util.ArrayUtil;
import com.crmeb.core.common.CommonApiResult;
import com.crmeb.core.common.CommonResult;
import com.github.pagehelper.Page;
import com.taobao.pac.sdk.cp.dataobject.request.MODUAN_ORDER_CREATE.request;
import com.taobao.pac.sdk.cp.dataobject.response.MODUAN_ORDER_CREATE.response;
import com.utils.*;
import com.zbkj.crmeb.chant.model.*;
import com.zbkj.crmeb.chant.service.*;
import com.zbkj.crmeb.enums.*;
import com.zbkj.crmeb.marketing.model.StoreCoupon;
import com.zbkj.crmeb.marketing.service.StoreCouponService;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.service.*;
import com.zbkj.crmeb.system.model.SystemGroupData;
import com.zbkj.crmeb.system.service.SystemGroupDataService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.crmeb.core.exception.CrmebException;
import com.crmeb.core.utils.TableNameUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.utils.vo.MatchImageVo;
import com.zbkj.crmeb.category.service.CategoryService;
import com.zbkj.crmeb.category.vo.CategoryTreeVo;
import com.zbkj.crmeb.chant.dto.ChannelDiscountDTO;
import com.zbkj.crmeb.chant.request.ChannelDiscountRequest;
import com.zbkj.crmeb.front.request.IndexStoreProductSearchRequest;
import com.zbkj.crmeb.front.request.ProductRequest;
import com.zbkj.crmeb.front.response.BuyerProductResDTO;
import com.zbkj.crmeb.front.response.BuyerProductResDTO.Product;
import com.zbkj.crmeb.front.response.BuyerProductResDTO.ProductSku;
import com.zbkj.crmeb.front.response.ProductDetailResponse;
import com.zbkj.crmeb.front.response.ProductResponse;
import com.zbkj.crmeb.front.response.StoreProductReplayCountResponse;
import com.zbkj.crmeb.front.vo.ActivityVo;
import com.zbkj.crmeb.merchant.admin.service.MerStoreProductService;
import com.zbkj.crmeb.merchant.api.service.MerProductService;
import com.zbkj.crmeb.store.dao.StoreProductDao;
import com.zbkj.crmeb.store.dto.ImItemResDTO;
import com.zbkj.crmeb.store.dto.ImItemResDTO.ImItemDTO;
import com.zbkj.crmeb.store.dto.ImProductInfoResDTO;
import com.zbkj.crmeb.store.dto.ImProductInfoResDTO.ImProductInfoDTO;
import com.zbkj.crmeb.store.dto.ImProductResDTO.ImProductDTO;
import com.zbkj.crmeb.store.dto.ImProductResDTO.ImProductItemDTO;
import com.zbkj.crmeb.store.dto.LeamProductResDTO.LeamGoodsRes;
import com.zbkj.crmeb.store.dto.LeamProductResDTO.LeamGoodsRes.LeamSku;
import com.zbkj.crmeb.store.request.StoreProductAttrValueRequest;
import com.zbkj.crmeb.store.request.StoreProductCrmebRequest;
import com.zbkj.crmeb.store.request.StoreProductReplySearchRequest;
import com.zbkj.crmeb.store.response.PriceResult;
import com.zbkj.crmeb.store.response.StoreCartResponse;
import com.zbkj.crmeb.store.response.StoreProductAttrValueResponse;
import com.zbkj.crmeb.store.response.StoreProductDetailNormResponse;
import com.zbkj.crmeb.store.response.StoreProductGroupActivityResponse;
import com.zbkj.crmeb.store.response.StoreProductReplyResponse;
import com.zbkj.crmeb.store.response.StoreProductResponse;
import com.zbkj.crmeb.store.response.StoreProductStoreInfoResponse;
import com.zbkj.crmeb.store.utilService.OrderUtils;
import com.zbkj.crmeb.system.model.SystemConfig;
import com.zbkj.crmeb.system.service.SystemAttachmentService;
import com.zbkj.crmeb.system.service.SystemConfigService;
import com.zbkj.crmeb.tools.model.MoneyExchange;
import com.zbkj.crmeb.tools.service.MoneyExchangeService;
import com.zbkj.crmeb.user.model.User;
import com.zbkj.crmeb.user.model.UserMemberRecord;
import com.zbkj.crmeb.user.service.UserMemberRecordService;
import com.zbkj.crmeb.user.service.UserService;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;

/**
* @author Mr.Zhang
* @Description IndexServiceImpl 接口实现
* @since 2020-04-13
*/
@Slf4j
@Service
public class MerProductServiceImpl implements MerProductService {
    private ExecutorService thread = ThreadPoolUtils.getThread();
    @Autowired
    private MerStoreProductService storeProductService;
    @Resource
    private StoreProductNormService storeProductNormService;
    @Autowired
    private StoreProductAttrService storeProductAttrService;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    private StoreProductAttrResultService storeProductAttrResultService;
    @Autowired
    private StoreProductDescriptionService storeProductDescriptionService;
    @Autowired
    private SystemAttachmentService systemAttachmentService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private StoreProductReplyService storeProductReplyService;
    @Autowired
    private UserService userService;
    @Autowired
    private StoreProductRelationService storeProductRelationService;
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private StoreBrandService storeBrandService;
    @Autowired
    PriceUtil priceUtil;
    @Autowired
    EuropeUtil europeUtil;
    @Autowired
    ProductUtil productUtil;
    @Autowired
    SourceProductUtil sourceProductUtil;
    @Autowired
    RestTemplateUtil restTemplateUtil;
    @Autowired
    private StoreOrderInfoService storeOrderInfoService;
    @Resource
    private StoreProductDao dao;
    @Autowired
    SupplierService supplierService;
    @Autowired
    ICategoryMatchService categoryMatchService;
    @Autowired
    ChannelCategoryConfigService channelCategoryConfigService;
    @Autowired
    private StoreProductMerService storeProductMerService;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    OrderUtils orderUtils;
    @Autowired
    private MoneyExchangeService moneyExchangeService;
    @Autowired
    private ProductConvertUtil productConvertUtil;
    @Autowired
    private ChannelActivityService channelActivityService;
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private UserMemberRecordService userMemberRecordService;
    @Autowired
    private ChannelMemberLevelService channelMemberLevelService;
    @Autowired
    private StoreSaleAnalysisService storeSaleAnalysisService;
    @Autowired
    private ChannelGroupBookingService channelGroupBookingService;
    @Autowired
    private ChannelFreeShippingActivityService channelFreeShippingActivityService;
    @Autowired
    private ChannelDiscountService channelDiscountService;
    @Autowired
    private StoreCouponService storeCouponService;
    @Autowired
    private StoreProductCouponService storeProductCouponService;
    @Autowired
    private ChannelDiscountPackageGoodsService channelDiscountPackageGoodsService;
    @Autowired
    private SystemGroupDataService systemGroupDataService;
    @Autowired
    private UserCommissionService userCommissionService;

    @Resource
    private KeyValueService keyValueService;

    /**
     * 首页产品的轮播图和产品信息
     * @param request IndexStoreProductSearchRequest 参数
     * @author Mr.Zhang
     * @since 2020-06-02
     * @return CommonPage<ProductResponse>
     */
    @Override
    public CommonPage<ProductResponse> getIndexProduct(IndexStoreProductSearchRequest request, PageParamRequest pageParamRequest, Integer leaderId) {
    	// 小编推荐
    	if (BooleanUtil.isTrue(request.getIsBest())) {
            int productCount = storeProductMerService.count(Wrappers.<StoreProductMer>lambdaQuery().eq(StoreProductMer::getIsBest, true));
            if (0 >= productCount) {
                return CommonPage.restPage(new ArrayList<>());
            }
            request.setBestIds(Collections.singletonList(0));
        }
        PageInfo<StoreProduct> productPage = new PageInfo<StoreProduct>();
        List<StoreProduct> storeProductList = new ArrayList<>();
        log.info("查询请求参数 request:{}", JSONObject.toJSONString(request));
        productPage = storeProductService.getList(request, pageParamRequest);
        storeProductList = productPage.getList();
        log.info("查询结果 storeProductList:{}", JSONObject.toJSONString(storeProductList));
        if (CollectionUtils.isEmpty(storeProductList)) {
            return CommonPage.restPage(new ArrayList<>());
        }
        // 匹配详情属性
        productConvertUtil.convertProductV3(storeProductList, leaderId);
        // 数据处理
        List<ProductResponse> productResponseArrayList = new ArrayList<>();
        dealProductResponse(storeProductList, productResponseArrayList, request.getMerId());

        // todo 金额转换为0
//        for(ProductResponse item: productResponseArrayList) {
//            userCommissionService.setPreferentialPrice(null, item, null, request.getMerId());
//        }
        CommonPage<ProductResponse> productResponseCommonPage = CommonPage.restPage(productResponseArrayList);
        productResponseCommonPage.setTotal(productPage.getTotal());
        productResponseCommonPage.setTotalPage(productPage.getPages());

        return productResponseCommonPage;
    }

    /**
     * 首页产品的轮播图和产品信息
     * @param request IndexStoreProductSearchRequest 参数
     * @author Mr.Zhang
     * @since 2020-06-02
     * @return CommonPage<ProductResponse>
     */
    @Override
    public CommonPage<ProductResponse> getShopProduct(IndexStoreProductSearchRequest request, PageParamRequest pageParamRequest) {

        PageInfo<StoreProduct> productPage = new PageInfo<StoreProduct>();
        List<StoreProduct> storeProductList = new ArrayList<>();
        log.info("查询请求参数 request:", JSONObject.toJSONString(request));
        productPage = storeProductService.getShopProductList(request, pageParamRequest);
        storeProductList = productPage.getList();
        log.info("查询结果 storeProductList:", JSONObject.toJSONString(storeProductList));
        if (CollectionUtils.isEmpty(storeProductList)) {
            return CommonPage.restPage(new ArrayList<>());
        }
        // 匹配详情属性
        productConvertUtil.convertProductV3(storeProductList, null);
        // 数据处理
        List<ProductResponse> productResponseArrayList = new ArrayList<>();
        dealProductResponse(storeProductList, productResponseArrayList, request.getMerId());

        // todo 金额转换为0
//        for(ProductResponse item: productResponseArrayList) {
//            userCommissionService.setPreferentialPrice(null, item, null, request.getMerId());
//        }
        CommonPage<ProductResponse> productResponseCommonPage = CommonPage.restPage(productResponseArrayList);
        productResponseCommonPage.setTotal(productPage.getTotal());
        productResponseCommonPage.setTotalPage(productPage.getPages());

        return productResponseCommonPage;
    }

    /**
     * 首页产品的轮播图和产品信息
     * @param request IndexStoreProductSearchRequest 参数
     * @author Mr.Zhang
     * @since 2020-06-02
     * @return CommonPage<ProductResponse>
     */
    @Override
    public List<ProductResponse> getProductList(IndexStoreProductSearchRequest request, PageParamRequest pageParamRequest, Integer leaderId) {

        List<StoreProduct> storeProductList = storeProductService.getListV2(request, pageParamRequest);
        if (CollectionUtils.isEmpty(storeProductList)) {
            return new ArrayList<>();
        }
        storeProductList.forEach(e -> {
            if(null != e.getPrice()){
                e.setOldPrice(e.getPrice());
            }
        });
        // 匹配详情属性
        productConvertUtil.convertProductV3(storeProductList, leaderId);
        // 数据处理
        List<ProductResponse> productResponseArrayList = new ArrayList<>();
        dealProductResponse(storeProductList, productResponseArrayList, request.getMerId());

        return productResponseArrayList;
    }

    /**
     * 获取首页推荐
     * @param request
     * @param pageParamRequest
     * @return
     */
    @Override
    public CommonPage<ProductResponse> getBestProductList(IndexStoreProductSearchRequest request, PageParamRequest pageParamRequest) {
        ChannelMerchant channelMerchant = channelMerchantService.getById(request.getMerId());
        List<String> brandIdsList= JSON.parseArray(channelMerchant.getBrandIds(), String.class);
        List<String> suppliersIdList = JSON.parseArray(channelMerchant.getSuppliersIds(), String.class);
        List<String> tempIdList = JSON.parseArray(channelMerchant.getTempId(), String.class);
        if (CollectionUtils.isNotEmpty(suppliersIdList)) {
            Supplier supplier = supplierService.getSupplierBarcode(request.getMerId());
            if (null != supplier) {
                //商户如果是供应商的话 查询商户自建的商品 默认传入商户配置的供应商id
                suppliersIdList.add(supplier.getId().toString());
            }
        }
        List<Integer> cateIdList = categoryMatchService.selectCategoryMatchDisable(request.getMerId()).stream().map(CategoryMatch::getId).collect(Collectors.toList());
        request.setInvisibleCateIds(cateIdList);
        request.setTableNameMp(TableNameUtil.getProductMerName(request.getMerId()));
        request.setBrandIdList(brandIdsList).setSuppliersIdList(suppliersIdList).setTempIdList(tempIdList);
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<StoreProduct> storeProductList = storeProductMerService.getProductIdList(request);
        // 匹配详情属性
        productConvertUtil.convertProduct(storeProductList);

        if (CollectionUtils.isEmpty(storeProductList)) {
            return CommonPage.restPage(new ArrayList<>());
        }
        CommonPage<StoreProduct> storeProductCommonPage = CommonPage.restPage(storeProductList);
        //处理返回数据
        List<ProductResponse> productResponseArrayList = new ArrayList<>();
        dealProductResponse(storeProductList, productResponseArrayList, request.getMerId());

        CommonPage<ProductResponse> productResponseCommonPage = CommonPage.restPage(productResponseArrayList);
        BeanUtils.copyProperties(storeProductCommonPage, productResponseCommonPage, "list");

        return productResponseCommonPage;
    }

    /**
     * 商品列表 - 处理返回数据
     * @param storeProductList
     * @param productResponseArrayList
     */
    private void dealProductResponse(List<StoreProduct> storeProductList, List<ProductResponse> productResponseArrayList, Integer merId) {
        if(CollectionUtils.isNotEmpty(storeProductList)){
            //用户等级会员
            User user = userService.getInfo();
            List<ChannelMemberLevel> memberLevelList = new ArrayList<>();
            if(user != null && user.getLevel() != 0 && user.getLevel() != 1){
                memberLevelList = channelMemberLevelService.getMemberLevelList(0, merId, Collections.singletonList(user.getLevel()));
            }
            ChannelMerchant channelMerchant = channelMerchantService.getChannelMerchantByMerId(merId);
            // 计算价格
            priceUtil.calcProductPrice(storeProductList, merId, AreaTypeEnum.CN.getType());
            priceUtil.calcMemberLevelProductPrice(storeProductList,channelMerchant,memberLevelList);
            //计算会员折扣价格
            priceUtil.calcMemberDiscountPrice(storeProductList, merId,true);
        }
        for (StoreProduct storeProduct : storeProductList) {
            // 商品发货地
            ProductResponse productResponse = new ProductResponse();
            BeanUtils.copyProperties(storeProduct, productResponse);
//            productResponse.setCateId(CrmebUtil.stringToArray(storeProduct.getCateId()));
            productResponse.setStockArea(StockAreaTempEnum.getByTempId(storeProduct.getTempId()).getStockAreaCode());
            productResponse.setStockAreaName(StockAreaTempEnum.getByTempId(storeProduct.getTempId()).getStockAreaName());
//            productResponse.setSales(storeProduct.getSales() + storeProduct.getFicti());
            //尺码
            List<StoreProductAttrValue> productAttrValueList = storeProductAttrValueService.list(Wrappers.lambdaQuery(StoreProductAttrValue.class)
            		.eq(StoreProductAttrValue::getProductId, storeProduct.getId())
                    .gt(StoreProductAttrValue::getStock, 0));
            Set<String> set = new LinkedHashSet<>();
            for (StoreProductAttrValue attrValue : productAttrValueList) {
                try {
                    JSONObject jsonObject = JSONObject.parseObject(attrValue.getAttrValue());
                    List<Object> collect = Stream.of(jsonObject.get("尺寸"), jsonObject.get("尺码"), jsonObject.get("大小"), jsonObject.get("腰带尺寸")).collect(Collectors.toList());
                    collect.removeIf(Objects::isNull);
                    set.add(collect.get(0).toString());
                } catch (Exception e){
                    log.info("该商品无尺寸信息,商品id：{}",attrValue.getProductId());
                }
            }
            productResponse.setSizeList(new ArrayList<>(set));
            //品牌处理
            StoreBrand storeBrand = null;
            if(null != storeProduct.getBrandId()) {
                storeBrand = storeBrandService.getById(storeProduct.getBrandId());
            }
            productResponse.setBrand(storeBrand);

            //市场价和折扣处理
            dealCalcDiscount(productResponse, storeProduct,merId);

            //主图和详情图压缩替换处理
            compressProductImage(productResponse, storeProduct);

            productResponseArrayList.add(productResponse);
        }
    }

    /**
     * 商品列表 - 主图和详情图压缩替换处理
     */
    private void compressProductImage(ProductResponse productResponse, StoreProduct storeProduct) {
        //详情图
        String sliderImage = storeProduct.getSliderImage();

        if (StringUtils.isNotBlank(sliderImage)) {
            List<String> sliderImageList = JSONObject.parseArray(sliderImage, String.class);
            productResponse.setSliderImage(sliderImageList);
        }
    }

    /**
     * 商品列表 - 市场价和折扣处理
     * @param productResponse
     */
    private void dealCalcDiscount(ProductResponse productResponse, StoreProduct storeProduct,Integer merId) {
        //市场价和折扣处理
        BigDecimal otPrice = storeProduct.getOtPrice();
        BigDecimal calcDiscount = new BigDecimal(0);
        //判断自建商品和2c商品
        ChannelMerchant channelMerchant = channelMerchantService.getById(merId);
        BigDecimal price;
        if (channelMerchant!=null&&channelMerchant.getAppletType()==1&&storeProduct.getTaxAndSecondPrice()!=null) {
            price= productResponse.getPrice().add(storeProduct.getTaxAndSecondPrice());
        }else {
            price = productResponse.getPrice();
        }
        //市场价不为null或市场价大于0
        if (null != otPrice && otPrice.compareTo(new BigDecimal(0)) > 0) {
            productResponse.setOtPriceRmb(priceUtil.eur2RmbStatic(otPrice, storeProduct.getExchangeRate()));
            //折扣 = 售价/(市场价*汇率) , 注：市场价为港币
            calcDiscount = priceUtil.calcDiscount(price, otPrice, storeProduct.getExchangeRate());
        }
        if(null != calcDiscount && !(calcDiscount.compareTo(BigDecimal.ZERO) == 0) ){
            productResponse.setDiscount(calcDiscount.toString() + "折");
            productResponse.setOtPrice(storeProduct.getOtPrice());
        }
    }

    /**
     * 获取分类
     * @author Mr.Zhang
     * @since 2020-06-03
     * @return List<CategoryTreeVo>
     */
    @Override
    public List<CategoryTreeVo> getCategory() {
        return categoryService.getFrontListTree(Constants.CATEGORY_TYPE_PRODUCT, 1);
    }

    /**
     * 商品列表
     * @author Mr.Zhang
     * @since 2020-06-03
     * @return CommonPage<ProductResponse>
     */
    @Override
    public CommonPage<ProductResponse> getList(ProductRequest request, PageParamRequest pageParamRequest) throws Exception {
        IndexStoreProductSearchRequest indexStoreProductSearchRequest = new IndexStoreProductSearchRequest();
        BeanUtils.copyProperties(request, indexStoreProductSearchRequest);
        //条件查询
        productListConditionSearch(request, indexStoreProductSearchRequest);
        return getIndexProduct(indexStoreProductSearchRequest, pageParamRequest, null);
    }

    /**
     * 商品列表 - 图搜
     * @author Mr.Zhang
     * @since 2020-06-03
     * @return CommonPage<ProductResponse>
     */
    @Override
    public CommonPage<ProductResponse> getListByTuSou(MultipartFile targetImage, ProductRequest request, PageParamRequest pageParamRequest, Integer leaderId) throws Exception {
    	IndexStoreProductSearchRequest indexStoreProductSearchRequest = new IndexStoreProductSearchRequest();
        BeanUtils.copyProperties(request, indexStoreProductSearchRequest);
        // 条件拼接
        productListConditionSearch(request, indexStoreProductSearchRequest);
        // 图搜查询接口
        if (null != targetImage && !targetImage.isEmpty()) {
            productListSearchImage(targetImage, indexStoreProductSearchRequest);
        }
        indexStoreProductSearchRequest.setIsShow(1);
        CommonPage<ProductResponse> response = getIndexProduct(indexStoreProductSearchRequest, pageParamRequest,leaderId);
        // 热门搜索词记录
        SystemGroupData one = systemGroupDataService.getOne(Wrappers.<SystemGroupData>lambdaQuery()
                .eq(SystemGroupData::getKeywords, request.getKeyword())
                .eq(SystemGroupData::getMerId, request.getMerId())
                .last("limit 1"));
        if (Objects.nonNull(one)) {
            one.setSort(one.getSort() + 1);
            JSONObject value = JSONObject.parseObject(one.getValue());
            Integer sort = value.getInteger("sort") + 1;
            value.put("sort", sort);
            one.setValue(value.toJSONString());
            systemGroupDataService.updateById(one);
        } else {
            SystemGroupData systemGroupData = new SystemGroupData();
            systemGroupData.setGid(Constants.GROUP_DATA_ID_INDEX_KEYWORDS);
            JSONObject value = new JSONObject();
            JSONObject fields = new JSONObject();
            JSONArray fieIdsArray = new JSONArray();
            fields.put("name", "title");
            fields.put("title", "title");
            fields.put("value", request.getKeyword());
            fieIdsArray.add(fields);
            value.put("fields", fieIdsArray);
            value.put("id", 102);
            value.put("sort", 1);
            systemGroupData.setValue(value.toJSONString());
            systemGroupData.setSort(1);
            systemGroupData.setStatus(false);
            systemGroupData.setMerId(request.getMerId());
            systemGroupData.setKeywords(request.getKeyword());
            systemGroupDataService.save(systemGroupData);
        }

        return response;
    }

    /**
     * 图像搜索 - 以图搜图
     * @param searchRequest
     */
    private void productListSearchImage(MultipartFile targetImage, IndexStoreProductSearchRequest searchRequest) throws Exception {

        List<String> barCodeArr = new ArrayList<>();

        //搜索相似图片barCode
        byte[] imgBytes = targetImage.getBytes();
        List<MatchImageVo> matchList = ImageSearchUtils.searchImage(imgBytes);

        //赋值barCode集合查询
        if (CollectionUtils.isNotEmpty(matchList)) {
            for (MatchImageVo matchImage : matchList) {
                String entityId = matchImage.getProductId();
                if (StringUtils.isNotBlank(entityId)) {
                    barCodeArr.add(entityId);
                }
            }
        }
        //图搜结果barCode集合作为查询条件
        searchRequest.setBarCodeArr(barCodeArr);
    }

    /**
     * 商品列表 - 条件查询
     */
    private void productListConditionSearch(ProductRequest request, IndexStoreProductSearchRequest indexStoreProductSearchRequest) {
        List<Integer> categoryIdList;
        // 获得三级分类id
        if (request.getCid() != null && request.getCid() != 0) {
            categoryIdList = categoryMatchService.getThreeChildVoListByPid(request.getCid()).stream().map(CategoryMatch::getId).collect(Collectors.toList());
            indexStoreProductSearchRequest.setCateId(categoryIdList);
        }
        // 专区id
        if (request.getZoneId() != null && request.getZoneId() != 0) {
            indexStoreProductSearchRequest.setZoneId(request.getZoneId());
        }
        // 获得列表三级分类id
        if (StringUtils.isNotBlank(request.getCids())) {
            String[] cid = request.getCids().split(",");
            categoryIdList = new ArrayList<>();
            for (String id : cid) {
                List<Integer> childIdList = categoryMatchService.getThreeChildVoListByPid(Integer.parseInt(id)).stream().map(CategoryMatch::getId).collect(Collectors.toList());
                categoryIdList.addAll(childIdList);
            }
            indexStoreProductSearchRequest.setCateId(categoryIdList);
        }
        indexStoreProductSearchRequest.setType(1);
        indexStoreProductSearchRequest.setKeywords(request.getKeyword());
        indexStoreProductSearchRequest.setIsNew(request.getNews());
        indexStoreProductSearchRequest.setShowIds(Collections.singletonList(0));
    }

    /**
     * 商品详情
     * @author Mr.Zhang Edit by stivpeim 2020-6-30
     * @since 2020-06-03
     * @return ProductDetailResponse
     */
    @Override
    public StoreProductDetailNormResponse getDetailNorm(Integer id, Integer merId,Integer activityId, String groupId) {
        StoreProductDetailNormResponse response = new StoreProductDetailNormResponse();
        StoreProduct product = storeProductService.getById(id);
        if(Objects.isNull(product)) {
        	throw new CrmebException("标准商品不存在!");
        }
        // 暂写死固定自营小程序私域图权限
		if (18 != merId && 30 != merId/* && 45 != merId && 47 != merId*/) {
			product.setMt(null);
			product.setSp2(null);
        }
        
        ChannelMerchant channelMerchant = channelMerchantService.getById(merId);
        response.setChannelMerchant(channelMerchant);
        Integer normId = product.getNormId();
        try {
            // 校验是否支持自提
            boolean isAllowSelfPickUp = orderUtils.checkAllowSelfPickUp(merId, id, groupId);
            if(isAllowSelfPickUp){
                response.setIsAllowSelfPickUp(SwitchEnum.OPEN.getCode());
            }
        }catch (Exception e){
            log.error("校验是否支持自提异常，", e);
        }
        if(null != normId) {
            response.setProductNorm(storeProductNormService.getById(normId));
            response.setProducts(listDetail(normId, merId,groupId));
            //记录商品访客数量 author:duyb
            try {
                saveVisitorNumber(product,merId);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("记录商品访客数量出错!,exception:",e);
            }
        } else {
            ProductDetailResponse productDetailResponse = getDetail(id, merId,activityId, groupId);
            List<ProductDetailResponse> productDetailResponses = Arrays.asList(productDetailResponse);
            response.setProducts(productDetailResponses);
            
            if(CollectionUtils.isNotEmpty(productDetailResponses)) {
                StoreProductNorm norm = new StoreProductNorm();
                BeanUtils.copyProperties(productDetailResponses.get(0).getStoreInfo(), norm);
                response.setProductNorm(norm);
            }
        }
        // todo 金额转换为0
//        for(ProductDetailResponse item: response.getProducts()) {
//            userCommissionService.setPreferentialPrice(item, null, null, merId);
//        }
        log.info("多供应商商品详情 response：{}", JSONObject.toJSONString(response));

        return response;
        
    }
    
    /**
     * 商品详情
     * @author Mr.Zhang Edit by stivpeim 2020-6-30
     * @since 2020-06-03
     * @return ProductDetailResponse
     */
    @Override
    public ProductDetailResponse getDetail(Integer id, Integer merId, Integer activityId, String groupId) {
        ProductDetailResponse productDetailResponse = new ProductDetailResponse();
        // 校验是否支持自提
        try {
            boolean isAllowSelfPickUp = orderUtils.checkAllowSelfPickUp(merId, id, groupId);
            if (isAllowSelfPickUp) {
                productDetailResponse.setIsAllowSelfPickUp(SwitchEnum.OPEN.getCode());
            }
        }catch (Exception e){
            log.error("校验是否支持自提异常，", e);
        }
        try {
            StoreProduct storeProduct = storeProductService.getById(id);
            ChannelMerchant channelMerchant = channelMerchantService.getById(merId);
            productDetailResponse.setChannelMerchant(channelMerchant);
            // 更新时间超过一小时的商品重新获取
            if (null != storeProduct && null != storeProduct.getLastPushTime() && 60 < ((System.currentTimeMillis() - storeProduct.getLastPushTime().getTime()) / 1000 / 60)) {
                updateProductByNow(storeProduct);
            }
            
            StoreProductResponse  productResponse = storeProductService.getByProductId(id, merId,true,true, groupId, false);
            /*if(productResponse.getNormId() != null){
                StoreProductNorm productNorm = storeProductNormService.getById(productResponse.getNormId());
                if(productNorm != null){
                    productResponse.setStoreInfo(productNorm.getStoreInfo());
                    productResponse.setSliderImage(productNorm.getSliderImage());
                    productResponse.setGwpp1(null);
                    productResponse.setGwmt1(null);
                    productResponse.setSp1(null);
                    productResponse.setSp(null);
                    productResponse.setSp2(null);
                    productResponse.setSp3(null);
                    productResponse.setMt(null);
                    productResponse.setMt1(null);
                    productResponse.setMx1(null);
                }
            }*/
            StoreProductStoreInfoResponse storeInfo = new StoreProductStoreInfoResponse();
            BeanUtils.copyProperties(productResponse, storeInfo);
            // 暂写死固定自营小程序私域图权限
			if (18 != merId && 30 != merId/* && 45 != merId && 47 != merId*/) {
            	storeInfo.setMt(null);
            	storeInfo.setSp2(null);
            }
            
            storeInfo.setUserLike(false);
            storeInfo.setUserCollect(false);
            storeInfo.setVideoLink(productResponse.getVideo());
            // 设置点赞和收藏
            User user = userService.getInfo();
            if (null != user && null != user.getUid()) {
                storeInfo.setUserLike(storeProductRelationService.getLikeOrCollectByUser(user.getUid(), id, true).size() > 0);
                storeInfo.setUserCollect(storeProductRelationService.getLikeOrCollectByUser(user.getUid(), id, false).size() > 0);
                user = userService.updateForPromoter(user);
                productDetailResponse.setPriceName(getPacketPriceRange(productResponse, user.getIsPromoter()));
            }
            //2c运税费加到价格里
            BigDecimal price = new BigDecimal(0);
            if (channelMerchant!=null&&channelMerchant.getAppletType() == 1&&storeInfo.getTaxAndSecondPrice()!=null) {
                price= storeInfo.getPrice().add(storeInfo.getTaxAndSecondPrice());
            }else {
                price = storeInfo.getPrice();
            }
            // 通过原价算折扣率
            //如果这扣率大于10，则不显示
            if (storeInfo.getOtPrice() != null && storeInfo.getOtPrice().intValue() > 0) {
                BigDecimal bigDecimal = priceUtil.calcDiscount(price, storeInfo.getOtPrice(), productResponse.getExchangeRate());
                if (null == bigDecimal) {
                    storeInfo.setDiscount(null);
                } else {
                    storeInfo.setDiscount(bigDecimal.toString() + "折");
                }
            }
			// 满减送活动
			ChannelDiscountDTO channelDiscountDTO = channelDiscountService.checkGoods2ChannelDiscount(merId, storeProduct.getId(), null);
			storeInfo.setChannelDiscountDescription(channelDiscountDTO.getDescription());
            storeInfo.setChannelDiscountGiftProductInfo(channelDiscountDTO.getGiftGoods());
            storeInfo.setStockAreaName(StockAreaTempEnum.getByTempId(storeInfo.getTempId()).getStockAreaName());
            storeInfo.setSales(storeInfo.getSales());
            productDetailResponse.setStoreInfo(storeInfo);
            
            // 根据制式设置attr属性
            setSkuAttr(id, productDetailResponse, productResponse);
            
            //分类未启用时设置商品为下架状态
            List<CategoryMatch> enableCategoryMatch = categoryMatchService.getCategoryMatch(merId, storeInfo.getCateId());
            if (CollectionUtils.isEmpty(enableCategoryMatch)){
                storeInfo.setIsShow(false);
            }
            //查询当前商品是否存在活动
            ChannelActivity activity;
            if(activityId != null){
                activity = channelActivityService.getById(activityId);
            }else {
                activity = channelActivityService.getOne(Wrappers.<ChannelActivity>lambdaQuery()
                        .eq(ChannelActivity::getIsDel,0)
                        .eq(ChannelActivity::getMerId, merId)
                        .gt(ChannelActivity::getEndTime, new Date())
                        .inSql(ChannelActivity::getId, "SELECT activity_id from eb_store_product_activity where product_id = " + id)
                        .orderByAsc(ChannelActivity::getStartTime)
                        .last("LIMIT 1")
                );
            }
            if(activity != null){
                List<StoreProductAttrValueResponse> productValues = productDetailResponse.getProductValues();
                List<StoreProductAttrValue> valueList = new ArrayList<>();
                List<StoreProductAttrValueResponse> attrValueList = productResponse.getAttrValue();
                for (StoreProductAttrValueResponse attrValue : attrValueList) {
                    StoreProductAttrValue value = new StoreProductAttrValue();
                    BeanUtils.copyProperties(attrValue,value);
                    valueList.add(value);
                }
                priceUtil.calcSpikePrice(valueList,activity.getId(),merId);
                BigDecimal minSpikePrice = valueList.stream().map(StoreProductAttrValue::getSpikePrice).min(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
                if(CollectionUtils.isNotEmpty(productValues)){
                    Map<String, StoreProductAttrValue> valueMap = valueList.stream().collect(Collectors.toMap(StoreProductAttrValue::getSourceSkuId, e -> e));
                    for (StoreProductAttrValueResponse valueResponse : productValues) {
                        valueResponse.setSpikePrice(valueMap.get(valueResponse.getSourceSkuId()).getSpikePrice());
                    }
                    //最低价
                    minSpikePrice = productValues.stream().map(StoreProductAttrValueResponse::getSpikePrice).min(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
                }
                storeInfo.setSpikePrice(minSpikePrice);
                ActivityVo activityVo = new ActivityVo();
                activityVo.setStartTime(activity.getStartTime());
                activityVo.setEndTime(activity.getEndTime());
                activityVo.setPreheatingStartTime(activity.getPreheatingStartTime());
                activityVo.setPreheatingEndTime(activity.getPreheatingEndTime());
                activityVo.setCrowd(activity.getCrowd());
                activityVo.setLimitTotal(activity.getLimitTotal());
                //返回用户类型
                List<Integer> list = new ArrayList<>();
                if(user != null){
                    list.add(1);
                    // 无订单用户
                    int orderCount = storeOrderService.
                            count(Wrappers.<StoreOrder>lambdaQuery().eq(StoreOrder::getUid, user.getUid()));
                    if (0 == orderCount) {
                        list.add(2);
                    }
                    // 新用户
                    if (user.getCreateTime().getTime() > activity.getCreateTime().getTime()) {
                        list.add(3);
                    }
                    //查询用户是否已开启会员
                    int count  = userMemberRecordService.count(Wrappers.lambdaQuery(UserMemberRecord.class)
                            .eq(UserMemberRecord::getPaid,true)
                            .gt(UserMemberRecord::getExpirationTime,new Date())
                            .eq(UserMemberRecord::getUid,user.getUid()));
                    if (count > 0){
                        list.add(4);
                    }
                }
                activityVo.setIdentityTypeList(list);
                if(activity.getStartTime().after(new Date())){
                    if(activity.getPreheating() != 3 && activity.getPreheatingStartTime().before(new Date()) && activity.getPreheatingEndTime().after(new Date())){
                        activityVo.setCanBuy(activity.getPreheatingBuy());
                    }else {
                        activityVo.setCanBuy(1);
                    }
                }else {
                    if(activity.getLimitTotal() == 0){
                        //用户身份类型判断
                        activityVo.setCanBuy(list.contains(activityVo.getCrowd()) ? 2 : 1);
                    }else {
                        if(user != null){
                            int count = storeOrderInfoService.count(Wrappers.<StoreOrderInfo>lambdaQuery()
                                    .eq(StoreOrderInfo::getActivityId, activity.getId())
                                    .ne(StoreOrderInfo::getStatus,5)
                                    .gt(StoreOrderInfo::getCreateTime, activity.getStartTime())
                                    .inSql(StoreOrderInfo::getOrderId, "SELECT id FROM eb_store_order where mer_id = " + merId + " and uid = "+ user.getUid())
                            );
                            if(list.contains(activityVo.getCrowd())){
                                activityVo.setCanBuy(activity.getLimitTotal() > count ? 2 : activity.getLimited());
                            }else {
                                activityVo.setCanBuy(activity.getLimitTotal() > count ? 1 : activity.getLimited());
                            }
                        }else {
                            activityVo.setCanBuy(2);
                        }
                    }
                }
                productDetailResponse.setActivityVo(activityVo);
            }
            //记录商品访客数量 author:duyb
            try {
                saveVisitorNumber(storeProduct,merId);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("记录商品访客数量出错!,exception:",e);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 拼团商品sku设置
        StoreProductGroupActivityResponse groupActivityResponse = channelGroupBookingService.getProductInfoByProductId(id, merId, true, groupId);
        if (Objects.nonNull(groupActivityResponse)){
            productDetailResponse.setGroupActivityValues(groupActivityResponse);
        }
        //满额包邮信息查询
        productDetailResponse.setFreeShippingActivity(channelFreeShippingActivityService.getProductInfo(id, merId));
        getProductCoupons(Collections.singletonList(productDetailResponse), merId);
        productDetailResponse.setDiscountPackageInfo(channelDiscountPackageGoodsService.getProductDiscountInfo(id, merId));

        // todo 金额转换为0
//        userCommissionService.setPreferentialPrice(productDetailResponse, null, null, merId);

        // 活动报名商品标记处理
        handleActivityProduct(productDetailResponse);

//        log.info("单供应商商品详情 productDetailResponse：{}", JSONObject.toJSONString(productDetailResponse));
        return productDetailResponse;
    }

    private void handleActivityProduct(ProductDetailResponse productDetailResponse) {
        if (null == productDetailResponse || null == productDetailResponse.getStoreInfo()){
            return;
        }
        StoreProductStoreInfoResponse storeInfo = productDetailResponse.getStoreInfo();
        Integer productId = storeInfo.getId();
        KeyValueDO keyValueDO = keyValueService.getByTypeCodeAndKey("ACTIVITY_APPLY_PRODUCTS", "活动报名商品", false);
        if (null == keyValueDO || StringUtils.isBlank(keyValueDO.getValue())){
            return;
        }
        String[] productIds = keyValueDO.getValue().split(",");
        if (ArrayUtil.contains(productIds, String.valueOf(productId))){
            productDetailResponse.setIsActiveApplyProduct(1);
        }
    }

    /**
     * 记录商品访客数量
     * @author duyb
     * @since 2020-10-12
     */
    private void saveVisitorNumber(StoreProduct storeProduct,Integer merId){
        StoreProductActive storeProductActive = storeSaleAnalysisService.getOne(Wrappers.<StoreProductActive>lambdaQuery()
                .eq(StoreProductActive::getMerId, merId)
                .eq(StoreProductActive::getProductId, storeProduct.getId())
                .eq(StoreProductActive::getStatisticsDate,DateUtil.nowDateTimeReturnDate("yyyy-MM-dd"))
        );
        if (storeProductActive==null){
            storeProductActive=new StoreProductActive();
            storeProductActive.setMerId(merId);
            storeProductActive.setProductId(storeProduct.getId());
            storeProductActive.setStoreName(storeProduct.getStoreName());
            storeProductActive.setCreateTime(DateUtil.nowDateTime());
            storeProductActive.setVisitorNumber(1);
            storeProductActive.setStatisticsDate(DateUtil.nowDateTimeReturnDate("yyyy-MM-dd"));
        }else {
            storeProductActive.setVisitorNumber(storeProductActive.getVisitorNumber()+1);
        }
        storeSaleAnalysisService.saveOrUpdate(storeProductActive);

    }

    private List<ProductDetailResponse> listDetail(Integer id, Integer merId, String groupId) {
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        productUtil.getChannelMerchantAuth(lambdaQueryWrapper, merId);
        lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
        lambdaQueryWrapper.eq(StoreProduct::getIsShow, true);
        lambdaQueryWrapper.eq(StoreProduct::getNormId, id);
        lambdaQueryWrapper.notInSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(merId) + " WHERE is_not_show = 1");
        
        List<StoreProduct> products = storeProductService.list(lambdaQueryWrapper);
        if (CollectionUtils.isEmpty(products)) {
            return null;
        }

		// 查询商家满减送活动
		ChannelDiscountRequest channelDiscountRequest = new ChannelDiscountRequest();
		channelDiscountRequest.setState(1);
		channelDiscountRequest.setStatus(true);
		List<ChannelDiscountDTO> channelDiscountDTOs = channelDiscountService.listEntity(merId, channelDiscountRequest);
        
        List<ProductDetailResponse> productDetailResponses = new ArrayList<>();
        for(StoreProduct storeProduct : products) {
            ProductDetailResponse productDetailResponse = new ProductDetailResponse();
            try {
                // 更新时间超过一小时的商品重新获取
                if (null != storeProduct && null != storeProduct.getLastPushTime() && 60 < ((System.currentTimeMillis() - storeProduct.getLastPushTime().getTime()) / 1000 / 60)) {
                    updateProductByNow(storeProduct);
                }
                
                StoreProductResponse productResponse = storeProductService.getByProductId(storeProduct.getId(), merId,true,true, groupId, false);
                StoreProductStoreInfoResponse storeInfo = new StoreProductStoreInfoResponse();
                BeanUtils.copyProperties(productResponse, storeInfo);
                // 暂写死固定自营小程序私域图权限
    			if (18 != merId && 30 != merId/* && 45 != merId && 47 != merId*/) {
    				storeInfo.setMt(null);
    				storeInfo.setSp2(null);
                }
                
//                storeInfo.setUserLike(false);
//                storeInfo.setUserCollect(false);
//                // 设置点赞和收藏
//                User user = userService.getInfo();
//                if (null != user && null != user.getUid()) {
//                    storeInfo.setUserLike(storeProductRelationService.getLikeOrCollectByUser(user.getUid(), id, true).size() > 0);
//                    storeInfo.setUserCollect(storeProductRelationService.getLikeOrCollectByUser(user.getUid(), id, false).size() > 0);
//                    user = userService.updateForPromoter(user);
//                    productDetailResponse.setPriceName(getPacketPriceRange(productResponse, user.getIsPromoter()));
//                }
                
                // 通过原价算折扣率
                //如果这扣率大于10，则不显示
                if (storeInfo.getOtPrice() != null && storeInfo.getOtPrice().intValue() > 0) {
                    BigDecimal bigDecimal = priceUtil.calcDiscount(storeInfo.getPrice(), storeInfo.getOtPrice(), storeProduct.getExchangeRate());
                    if (null == bigDecimal) {
                        storeInfo.setDiscount(null);
                    } else {
                        storeInfo.setDiscount(bigDecimal.toString() + "折");
                    }
                }
                storeInfo.setStockAreaName(StockAreaTempEnum.getByTempId(storeInfo.getTempId()).getStockAreaName());
                storeInfo.setSales(storeInfo.getSales());

				// 满减送活动
				ChannelDiscountDTO channelDiscountDTO = channelDiscountService.checkGoods2ChannelDiscount(merId, storeProduct.getId(), channelDiscountDTOs);
				storeInfo.setChannelDiscountDescription(channelDiscountDTO.getDescription());
                storeInfo.setChannelDiscountGiftProductInfo(channelDiscountDTO.getGiftGoods());
                productDetailResponse.setStoreInfo(storeInfo);
                
                // 根据制式设置attr属性
                setSkuAttr(id, productDetailResponse, productResponse);
                
                // 优品推荐
//                List<StoreProduct> storeProducts = storeProductService.getRecommendStoreProduct(storeInfo.getBrandId(), 18);
//                List<StoreProductRecommendResponse> storeProductRecommendResponses = new ArrayList<>();
//                for (StoreProduct product : storeProducts) {
//                    StoreProductRecommendResponse sPRecommendResponse = new StoreProductRecommendResponse();
//                    BeanUtils.copyProperties(product, sPRecommendResponse);
//                    sPRecommendResponse.setActivity(null); // todo 暂放 设置优品推荐中的拼团砍价秒杀属性
//                    storeProductRecommendResponses.add(sPRecommendResponse);
//                }
//                productDetailResponse.setGoodList(storeProductRecommendResponses);
                // 拼团商品sku设置
                StoreProductGroupActivityResponse groupActivityResponse = channelGroupBookingService.getProductInfoByProductId(storeInfo.getId(), merId, true, groupId);
                if (Objects.nonNull(groupActivityResponse)){
                    productDetailResponse.setGroupActivityValues(groupActivityResponse);
                }
                //满额包邮信息查询
                productDetailResponse.setFreeShippingActivity(channelFreeShippingActivityService.getProductInfo(id, merId));
                productDetailResponse.setDiscountPackageInfo(channelDiscountPackageGoodsService.getProductDiscountInfo(storeProduct.getId(), merId));
            } catch (Exception e) {
                e.printStackTrace();
            }

            
            productDetailResponses.add(productDetailResponse);
        }
        // 商品优惠券信息
        getProductCoupons(productDetailResponses, merId);
        
        return productDetailResponses;
    }

    /**
     * 评论列表
     * @author Mr.Zhang
     * @since 2020-06-03
     * @return List<StoreProductReply>
     */
    @Override
    public PageInfo<StoreProductReplyResponse> getReplyList(Integer id, Integer type, PageParamRequest pageParamRequest) {
        StoreProductReplySearchRequest storeProductReplySearchRequest = new StoreProductReplySearchRequest();
        storeProductReplySearchRequest.setIsDel(false);
        storeProductReplySearchRequest.setProductId(id.toString());
        storeProductReplySearchRequest.setType(type);
        return storeProductReplyService.getList(storeProductReplySearchRequest, pageParamRequest);
    }

    /**
     * 产品评价数量和好评度
     * @author Mr.Zhang
     * @since 2020-06-03
     * @return StoreProductReplayCountResponse
     */
    @Override
    public StoreProductReplayCountResponse getReplyCount(Integer id) {
        PageParamRequest pageParamRequest = new PageParamRequest();
        pageParamRequest.setLimit(1);

        StoreProductReplySearchRequest storeProductReplySearchRequest = new StoreProductReplySearchRequest();
        storeProductReplySearchRequest.setIsDel(false);
        storeProductReplySearchRequest.setProductId(id.toString());
        storeProductReplySearchRequest.setType(1);
        PageInfo<StoreProductReplyResponse> storeProductReplyServiceList = storeProductReplyService.getList(storeProductReplySearchRequest, pageParamRequest);
        Long goodCount = storeProductReplyServiceList.getTotal();

        storeProductReplySearchRequest.setType(2);
        storeProductReplyServiceList = storeProductReplyService.getList(storeProductReplySearchRequest, pageParamRequest);
        Long inCount = storeProductReplyServiceList.getTotal();

        storeProductReplySearchRequest.setType(3);
        storeProductReplyServiceList = storeProductReplyService.getList(storeProductReplySearchRequest, pageParamRequest);
        Long poorCount = storeProductReplyServiceList.getTotal();

        Long sumCount = goodCount + inCount + poorCount;

        //5星评分星数
        storeProductReplySearchRequest.setType(0);
        storeProductReplySearchRequest.setStar(5);
        storeProductReplyServiceList = storeProductReplyService.getList(storeProductReplySearchRequest, pageParamRequest);
        Long starCount = storeProductReplyServiceList.getTotal();

        //好评率
        String replyChance = "0";
        if (sumCount > 0 && starCount > 0) {
            replyChance = String.format("%.2f", ((starCount.doubleValue() / sumCount.doubleValue())));
        }

        Integer replyStar = storeProductReplyService.getSumStar(id);

        return new StoreProductReplayCountResponse(sumCount, goodCount, inCount, poorCount, replyChance, replyStar);
    }

    /**
     * 设置制式结构给attr属性
     * @param id 产品id
     * @param productDetailResponse 商品详情
     * @param productResponse 商品本身
     */
    private void setSkuAttr(Integer id, ProductDetailResponse productDetailResponse, StoreProductResponse productResponse) {
        List<HashMap<String, Object>> attrMapList = new ArrayList<>();
        // 根据制式设置sku属性
//        Map<String, StoreProductAttrValueResponse> skuMap = new IdentityHashMap<>();
//        List<StoreProductAttrValueResponse> spavrs = new ArrayList<>();
        List<StoreProductAttrValueResponse> responseArrayList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(productResponse.getAttrValue())) {
            //按价格升序,去重
            responseArrayList = productResponse.getAttrValue().stream().filter(e -> e.getStock() > 0)
                    .sorted(Comparator.comparing(StoreProductAttrValueResponse::getPrice))
                    .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(StoreProductAttrValueResponse::getSuk))), ArrayList::new));
//            for (StoreProductAttrValueResponse attrValue : productResponse.getAttrValue()) {
//                // 过滤掉没有库存的商品
//                if (attrValue.getStock() > 0) {
//                    skuMap.put(new String(attrValue.getSuk()), attrValue);
//                    spavrs.add(attrValue);
//                }
//            }
        }
        productDetailResponse.setProductValues(responseArrayList);
//        productDetailResponse.setProductValue(skuMap);
//        productDetailResponse.setProductValues(spavrs);
        if (CollectionUtils.isNotEmpty(productResponse.getAttr())) {
            for (StoreProductAttr attr : productResponse.getAttr()) {
                HashMap<String, Object> attrMap = new HashMap<>();
                attrMap.put("productId", attr.getProductId());
                attrMap.put("attrName", attr.getAttrName());
                attrMap.put("type", attr.getType());

                List<String> attrValues = new ArrayList<>();
                String trimAttr = attr.getAttrValues().replace("[", "").replace("]", "");
                if (attr.getAttrValues().contains(",")) {
                    attrValues = Arrays.asList(trimAttr.split(","));
                } else {
                    attrValues.add(trimAttr);
                }

                attrMap.put("attrValues", attrValues);
                // 设置带有优惠券标识的sku集合
                List<HashMap<String, Object>> attrValueMapList = new ArrayList<>();
                for (String attrValue : attrValues) {
                    HashMap<String, Object> attrValueMap = new HashMap<>();
                    attrValueMap.put("attr", attrValue);
                    attrValueMapList.add(attrValueMap);
                }
                attrMap.put("attrValue", attrValueMapList);
                attrMapList.add(attrMap);
            }
        }
        productDetailResponse.setProductAttr(attrMapList);
    }

    /**
     * 获取商品佣金区间
     * @param storeProductResponse 商品属性
     * @param isPromoter 是否推荐人
     * @return String 金额区间
     */
    @Override
    public String getPacketPriceRange(StoreProductResponse storeProductResponse, boolean isPromoter) {
        String priceName = "0";
        if (!isPromoter) {
            return priceName;
        }
        // 获取拥挤比例
        String BrokerageRatioString = systemConfigService.getValueByKey("store_brokerage_ratio");
        BigDecimal BrokerRatio = new BigDecimal(0);
        if (StringUtils.isNotBlank(BrokerageRatioString)) {
            BrokerRatio = new BigDecimal(BrokerageRatioString).multiply(new BigDecimal(0.01).setScale(2, BigDecimal.ROUND_HALF_DOWN));
        }
        BigDecimal maxPrice = null;
        BigDecimal minPrice = null;
        // 获取佣金比例区间 todo 这里的对象更换为map后需要重新计算
        if (storeProductResponse.getIsSub()) { // 是否单独分拥
            maxPrice = storeProductResponse.getAttrValue().stream().map(e -> e.getBrokerage()).reduce(BigDecimal.ZERO, BigDecimal::max);
            minPrice = storeProductResponse.getAttrValue().stream().map(e -> e.getBrokerage()).reduce(BigDecimal.ZERO, BigDecimal::min);
        } else {
            if (CollectionUtils.isNotEmpty(storeProductResponse.getAttrValue())) {
                BigDecimal _maxPrice = storeProductResponse.getAttrValue().stream().map(e -> e.getBrokerage()).reduce(BigDecimal.ZERO, BigDecimal::max);
                BigDecimal _minPrice = storeProductResponse.getAttrValue().stream().map(e -> e.getBrokerage()).reduce(BigDecimal.ZERO, BigDecimal::min);
                maxPrice = BrokerRatio.multiply(_maxPrice);
                minPrice = BrokerRatio.multiply((_minPrice));
            } else {
                maxPrice = BigDecimal.ZERO;
                minPrice = BigDecimal.ZERO;
            }
        }
        if (minPrice.compareTo(BigDecimal.ZERO) == 0 && maxPrice.compareTo(BigDecimal.ZERO) == 0) {
            priceName = "0";
        } else if (minPrice.compareTo(BigDecimal.ZERO) == 0 && maxPrice.compareTo(BigDecimal.ZERO) == 1) {
            priceName = maxPrice.toString();
        } else if (minPrice.compareTo(BigDecimal.ZERO) == 1 && maxPrice.compareTo(BigDecimal.ZERO) == 1) {
            priceName = minPrice.toString();
        } else if (minPrice.compareTo(maxPrice) == 0 && minPrice.compareTo(BigDecimal.ZERO) == 0) {
            priceName = maxPrice.toString();
        } else {
            priceName = minPrice.toString() + "~" + maxPrice.toString();
        }
        return priceName;
    }

    @Override
    public Integer getStockCount(Integer productId, String sourceSkuId, String size) {
        Integer count = 0 ;
        List<StoreOrderInfo> orderInfoList = storeOrderInfoService.getStoreOrderInfoList(productId);
        if(null!=orderInfoList && orderInfoList.size()>0){
            for(StoreOrderInfo info : orderInfoList){
                StoreCartResponse cart = JSON.parseObject(info.getInfo(), StoreCartResponse.class);
                //根据sourceSkuId 判断是否buyer
                if (StringUtils.isNotBlank(sourceSkuId)){
                    if(sourceSkuId.equals(cart.getProductInfo().getAttrInfo().getSourceSkuId())){
                        count = cart.getCartNum() + count;
                    }
                } else{
                    // 欧洲的 根据size判断 订单的数量
                    String[] sukArr = cart.getProductInfo().getAttrInfo().getSuk().split(",");
                    if(cart.getProductInfo().getAttrInfo().getSuk().contains(",")){
                        if(size.equals(sukArr[1])){
                            count = cart.getCartNum() + count;
                        }
                    }else{
                        if(size.equals(sukArr[0])){
                            count = cart.getCartNum() + count;
                        }
                    }
                }
            }
        }
        return count;
    }

    /**
     * 实时更新商品数据
     * @Description:  
     * @author daigb 
     * @param @param storeProduct
     * @return void
     * @throws
     */
    @Override
    public void updateProductByNow(StoreProduct storeProduct) {
        String barCode = storeProduct.getBarCode();
        Callable<String> call = new Callable<String>() {
            @Override
            public String call() throws Exception {
                // buyer商品
                if (storeProduct.getBarCode().startsWith(BarCodeEnum.BUYER.getCode().toString())) {
                    BuyerProductResDTO buyerProductResDTO = productUtil.getBuyerProductByBarCode(barCode);
                    // 处理主表数据
                    List<Product> buyerProducts = buyerProductResDTO.getProduct();
                    if (CollectionUtils.isEmpty(buyerProducts)) {
                        log.info("--------------- 实时查询buyer商品, 未取到数据, 直接下架并返回, 商品barCode: {}---------------", barCode);
                        soldOut(storeProduct.getId());
                        return barCode;
                    }
                    Product buyerProduct = buyerProducts.get(0);
                    // 金额不对时商品下架
                    if (Integer.parseInt(buyerProduct.getSalePrice()) <= 0) {
                        log.info("--------------- 实时查询buyer商品, 商品金额不是正常值, 直接下架并返回, 商品barCode: {}---------------", barCode);
                        soldOut(storeProduct.getId());
                        return barCode;
                    }
                    // 去除sku信息过滤库存为0的
                    int stock = 0;
                    List<ProductSku> buyerSkus = buyerProduct.getSkus();
                    List<ProductSku> productSkus = new ArrayList<ProductSku>();
                    for (ProductSku sku : buyerSkus) {
                        if (0 < sku.getStock()) {
                            stock += sku.getStock();
                            productSkus.add(sku);
                        }
                    }
                    // 没有规格时商品下架
                    if (CollectionUtils.isEmpty(productSkus)) {
                        log.info("--------------- 实时查询buyer商品, 商品没有正常库存规格, 直接下架并返回, 商品barCode: {}---------------", barCode);
                        soldOut(storeProduct.getId());
                        return barCode;
                    }
                    // 处理价格
                    buyerProduct = sourceProductUtil.priceAdjustBuyer2Crmeb(buyerProduct);
                    // 构建实体
                    StoreProductCrmebRequest storeProductCrmebRequest = sourceProductUtil.buildCrmebProduct(buyerProduct, productSkus);
                    saveProduct(storeProductCrmebRequest, storeProduct, stock);
                // 欧洲商品
                } else if (storeProduct.getBarCode().startsWith(BarCodeEnum.EUROPE.getCode().toString())) {
                    EuropeProduct europeProduct = productUtil.getEuropeByBarCode(barCode);
                    // 没有查询到商品
                    if (null == europeProduct || CollectionUtils.isEmpty(europeProduct.getSkuList())) {
                        log.info("--------------- 实时查询europe商品, 未取到数据, 直接下架并返回, 商品barCode: {}---------------", barCode);
                        soldOut(storeProduct.getId());
                        return barCode;
                    }
                    // 金额或者库存不对
                    if (1 != europeProduct.getPrice().compareTo(BigDecimal.ZERO) || 0 >= europeProduct.getStock()) {
                        log.info("--------------- 实时查询buyer商品, 商品金额不是正常值, 直接下架并返回, 商品barCode: {}---------------", barCode);
                        soldOut(storeProduct.getId());
                        return barCode;
                    }
                    // 构建商品
                    StoreProductCrmebRequest storeProductCrmebRequest = buildEuropeProduct(europeProduct);
                    // 处理价格
                    storeProductCrmebRequest = sourceProductUtil.priceAdjustEurope2Crmeb(storeProductCrmebRequest);
                    saveProduct(storeProductCrmebRequest, storeProduct, europeProduct.getStock());
                }
                // IM商品
                else if (storeProduct.getBarCode().startsWith(BarCodeEnum.IM.getCode().toString())) {
                    log.info("--------------------------实时查询IM商品：{}----------------------",storeProduct.getId());
                    String id = barCode.substring(4, barCode.length());
                    SystemConfig systemConfig = systemConfigService.getOne(Wrappers.<SystemConfig>lambdaQuery()
                            .eq(SystemConfig :: getName, Constants.IM_TOKEN)
                            .last("LIMIT 1")
                            );
//                    ImProductResDTO imProductResDTO = productUtil.getImProduct(Arrays.asList(id), systemConfig);
                    ImProductInfoResDTO imProductResDTO = productUtil.getImProductInfo(Collections.singletonList(id), systemConfig);
                    // 判定token失效
                    if(!imProductResDTO.getSuccess() && imProductResDTO.getError().contains("access-token")) {
                        systemConfig = productUtil.getImToken(systemConfig);
//                        imProductResDTO = productUtil.getImProduct(Arrays.asList(id), systemConfig);
                        imProductResDTO = productUtil.getImProductInfo(Collections.singletonList(id), systemConfig);
                    }
                    // 没有查询到商品
//                    List<ImProductDTO> imProductDTOs = imProductResDTO.getImProductDTOs();
                    List<ImProductInfoDTO> imProductDTOs = imProductResDTO.getImProductDTOs();
//                    if (CollectionUtils.isEmpty(imProductDTOs) || CollectionUtils.isEmpty(imProductDTOs.get(0).getItemIds())) {
//                        log.info("--------------- 实时查询IM商品, 未取到数据, 直接下架并返回, 商品barCode: {}---------------", barCode);
//                        soldOut(storeProduct.getId());
//                        return barCode;
//                    }
//                    if(imProductDTOs.get(0).getStatus() != 1){
//                        log.info("--------------- 实时查询IM商品, 商品不可售状态, 直接下架并返回, 商品barCode: {}---------------", barCode);
//                        soldOut(storeProduct.getId());
//                        return barCode;
//                    }
                    //分批查询item
                    List<ImItemDTO> itemAllList = new ArrayList<>();
                    int toIndex = 199;
                    List<String> itemIds = imProductDTOs.get(0).getItemIds();
                    if (itemIds.size() > toIndex) {
                        int listSize = itemIds.size();
                        for (int i = 0; i < itemIds.size(); i += toIndex) {
                            if (i + toIndex > listSize) {
                                toIndex = listSize - i;
                            }
                            List<String> newList = itemIds.subList(i, i + toIndex);
                            //查询商品item信息
                            ImItemResDTO imItemInfo = productUtil.getImItemInfo(newList, systemConfig);
                            if (!imItemInfo.getSuccess() && imItemInfo.getError().contains("access-token")) {
                                systemConfig = productUtil.getImToken(systemConfig);
                                imItemInfo = productUtil.getImItemInfo(imProductDTOs.get(0).getItemIds(), systemConfig);
                            }
                            //上架且库存大于0的items
                            List<ImItemDTO> itemList = imItemInfo.getImItemDTOs().stream().filter(e -> e.getStatus() == 1 && e.getQty() > 0).collect(Collectors.toList());
                            itemAllList.addAll(itemList);
                        }
                    }else {
                        //查询商品item信息
                        ImItemResDTO imItemInfo = productUtil.getImItemInfo(itemIds, systemConfig);
                        if(!imItemInfo.getSuccess() && imItemInfo.getError().contains("access-token")) {
                            systemConfig = productUtil.getImToken(systemConfig);
                            imItemInfo =productUtil.getImItemInfo(imProductDTOs.get(0).getItemIds(), systemConfig);
                        }
                        //上架且库存大于0的items
                        itemAllList = imItemInfo.getImItemDTOs().stream().filter(e -> e.getStatus() == 1 && e.getQty() > 0).collect(Collectors.toList());
                    }
                    // 库存不对
                    Integer stock = 0;
                    for(ImItemDTO item : itemAllList) {
                        stock += item.getQty();
                    }
                    if (0 >= stock) {
                        log.info("--------------- 实时查询IM商品, 商品无库存, 直接下架并返回, 商品barCode: {}---------------", barCode);
                        soldOut(storeProduct.getId());
                        return barCode;
                    }
                    // 构建商品
//                    StoreProductCrmebRequest storeProductCrmebRequest = buildImProduct(imProductDTOs.get(0), Constants.RATE_IM_2_CRMEB_FLOAT, Constants.RATE_IM_2_CRMEB, Constants.RATE_IM_2_CRMEB_COST);
                    StoreProductCrmebRequest storeProductCrmebRequest = buildImProductNew(imProductDTOs.get(0),itemAllList);
                    saveProduct(storeProductCrmebRequest, storeProduct, stock);
                //LEAM商品
                }
//                else if (barCode.startsWith(BarCodeEnum.LEAM.getCode().toString())) {
//                    int productId = Integer.parseInt(barCode.substring(4));
//                    LeamProductResDTO leamProductResDTO =productUtil.getLeamByProductId(productId);
//                    // 没有查询到商品
//                    if (null == leamProductResDTO || CollectionUtils.isEmpty(leamProductResDTO.getProducts())) {
//                        log.info("--------------- 实时查询leam商品, 未取到数据, 直接下架并返回, 商品barCode: {}---------------", barCode);
//                        soldOut(storeProduct.getId());
//                        return barCode;
//                    }
//                    LeamGoodsRes product = leamProductResDTO.getProducts().get(0);
//                    List<String> picList = Stream.of(product.getPic1(), product.getPic2(), product.getPic3(), product.getPic4(), product.getPic5()).collect(Collectors.toList());
//                    picList.removeIf(StringUtils::isBlank);
//                    if(CollectionUtils.isEmpty(picList)){
//                        log.info("--------------- 实时查询leam商品,该商品没有图片, 直接下架并返回, 商品barCode: {} ---------------",barCode);
//                        soldOut(storeProduct.getId());
//                        return barCode;
//                    }
//                    // 金额不对
//                    if (1 != product.getPrice().compareTo(BigDecimal.ZERO)) {
//                        log.info("--------------- 实时查询leam商品, 商品金额不是正常值, 直接下架并返回, 商品barCode: {}---------------", barCode);
//                        soldOut(storeProduct.getId());
//                        return barCode;
//                    }
//                    //sku为空
//                    if (CollectionUtils.isEmpty(product.getAvailableSize())) {
//                        log.info("--------------- 实时查询leam商品, sku为空, 直接下架并返回, 商品barCode: {}---------------", barCode);
//                        soldOut(storeProduct.getId());
//                        return barCode;
//                    }
//                    // 库存计算
//                    int stock = 0;
//                    for (LeamSku sku : product.getAvailableSize()) {
//                        stock += sku.getQty();
//                    }
//                    if(stock == 0){
//                        log.info("--------------- 实时查询leam商品, 库存为空, 直接下架并返回, 商品barCode: {}---------------", barCode);
//                        soldOut(storeProduct.getId());
//                        return barCode;
//                    }
//                    // 构建商品
//                    StoreProductCrmebRequest storeProductCrmebRequest = buildLeamProduct(product, product.getAvailableSize());
//                    saveProduct(storeProductCrmebRequest, storeProduct, stock);
//                }
                return barCode;
            }
        };
        
        try {
            Future<String> future = thread.submit(call);
            future.get(1000 * 10, TimeUnit.MILLISECONDS);
        } catch (TimeoutException ex) {
            System.out.println("--------------- 实时获取商品信息超时 ---------------");
            ex.printStackTrace();
        } catch (Exception e) {
            System.out.println("--------------- 实时获取商品信息处理失败 ---------------");
            e.printStackTrace();
        }
    }

    private StoreProductCrmebRequest buildLeamProduct(LeamGoodsRes product, List<LeamSku> availableSize) {
        // 主商品对象
        StoreProductCrmebRequest productRequest = null;
        try {
            List<String> collect = Stream.of(product.getPic1(), product.getPic2(), product.getPic3(), product.getPic4(), product.getPic5()).collect(Collectors.toList());
            collect.removeIf(com.baomidou.mybatisplus.core.toolkit.StringUtils::isBlank);
            String imageUrl = productUtil.selectImageUrl();
            List<String> picList = collect.stream().map(e -> e = imageUrl + e).collect(Collectors.toList());
            JSONArray gallery = JSONArray.parseArray(JSON.toJSONString(picList));
            // 成本价
            BigDecimal erpPrice = product.getDefaultPrice();
            // 售价
            PriceResult priceResult = priceUtil.eur2Rmb(product.getPrice());
            BigDecimal adjustPrice = priceResult.getPrice();
            // 品牌对应
            StoreBrand buyerStoreBrand = storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                    .eq(StoreBrand::getEnName, product.getBrand())
                    .eq(StoreBrand :: getType, ProductTypeEnum.LEAM)
                    .last("LIMIT 1")
            );
            StoreBrand storeBrand = null;
            if(null != buyerStoreBrand) {
                if(null != buyerStoreBrand.getSuperId()) {
                    storeBrand = storeBrandService.getById(buyerStoreBrand.getSuperId());
                }
            } else {
                storeBrand = storeBrandService.getById(5920);
            }
//             处理单独品牌价格(无法做成配置的)
//            if(null != storeBrand && "13De Marzo".equals(storeBrand.getEnName())) {
//                adjustPrice = PriceUtil.calePrice(erpPrice, "0.65");
//            }
            /***** 处理对象构建 *******/
            String barCode = BarCodeEnum.LEAM.getCode() + product.getProductId().toString();
            List<StoreProductAttr> attrList = new ArrayList<StoreProductAttr>();
            List<StoreProductAttrValueRequest> attrValueList = new ArrayList<StoreProductAttrValueRequest>();

            List<String> colorValueList = new ArrayList<>();
            List<String> sizeValueList = new ArrayList<>();
            // 规格
            StoreProductAttr storeProductAttr = new StoreProductAttr();
            storeProductAttr.setAttrName("尺寸");
            storeProductAttr.setType(0);
            storeProductAttr.setBarCode(barCode);
            // 颜色
            StoreProductAttr storeProductAttrColor = new StoreProductAttr();
            storeProductAttrColor.setAttrName("颜色");
            storeProductAttrColor.setType(0);
            storeProductAttrColor.setBarCode(barCode);

            for(LeamSku sku : availableSize) {
                // value对象
                StoreProductAttrValueRequest storeProductAttrValue = new StoreProductAttrValueRequest();
                storeProductAttrValue.setSourceSkuId(sku.getStockId());
                //suk
                storeProductAttrValue.setSuk(String.join(",", product.getColor(), sku.getSize()));
                storeProductAttrValue.setStock(sku.getQty());
                storeProductAttrValue.setPrice(adjustPrice);
                if(gallery.size() > 0) {
                    storeProductAttrValue.setImage(gallery.get(0).toString());
                }
                storeProductAttrValue.setCost(adjustPrice);
                storeProductAttrValue.setSourceCost(adjustPrice);
                storeProductAttrValue.setBarCode(barCode);
                storeProductAttrValue.setOtPrice(erpPrice);
                //发货地（欧洲）
                storeProductAttrValue.setTempId(StockAreaTempEnum.EUR.getTempId());

                LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
                if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(product.getColor())) {
                    linkedMap.put("颜色", product.getColor());
                    if(CollectionUtils.isEmpty(colorValueList)){
                        colorValueList.add(product.getColor());
                    }
                }
                if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(sku.getSize())) {
                    linkedMap.put("尺寸", sku.getSize());
                    sizeValueList.add(sku.getSize());
                }
                storeProductAttrValue.setAttrValue(linkedMap);
                attrValueList.add(storeProductAttrValue);
            }
            //attr对象
            if (CollectionUtils.isNotEmpty(colorValueList)) {
                storeProductAttrColor.setAttrValues(String.join(",", colorValueList));
                attrList.add(storeProductAttrColor);
            }
            if (CollectionUtils.isNotEmpty(sizeValueList)) {
                storeProductAttr.setAttrValues(String.join(",", sizeValueList));
                attrList.add(storeProductAttr);
            }

            productRequest = new StoreProductCrmebRequest();
            productRequest.setExchangeRate(priceResult.getExchangeRate());
            productRequest.setAttr(attrList);
            productRequest.setAttrValue(attrValueList);
            // 强制写一个 商户id 作为buyer商品标识标识
            productRequest.setMerId(CrmebMerchantEnums.LEAM.getMerchantId());
            productRequest.setContent(product.getDescription());
            // 商品keyword组合 (国际编码：style_code+fabric_code+color_code)
            productRequest.setKeyword(product.getStyleCode()+product.getFabricCode()+product.getColorCode());
            productRequest.setStoreInfo(product.getDescription());
            productRequest.setStoreName(product.getName());
            if(null != storeBrand) {
                productRequest.setBrandId(storeBrand.getId());
                productRequest.setBrandName(storeBrand.getEnName());
            }
            productRequest.setPrice(adjustPrice);
            productRequest.setOtPrice(erpPrice);
            productRequest.setCost(adjustPrice);
            productRequest.setSourceCost(adjustPrice);
            productRequest.setPromoteFlag(false);
            productRequest.setErpPromFlag(true);
            productRequest.setTempId(3);

            // 供应商
            Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
                    .eq(Supplier :: getSuppliersName, CrmebMerchantEnums.LEAM.getMerchantName())
                    .last("LIMIT 1")
            );
            if(null != supplier) {
                productRequest.setSuppliersId(supplier.getId());
                productRequest.setSuppliersName(supplier.getSuppliersName());
            }
            productRequest.setBarCode(barCode);
            // 分类
            CategoryMatch categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                    .eq(CategoryMatch::getType, CategoryTypeEnum.LEAM.getCode())
                    .eq(CategoryMatch::getOthCategoryId, product.getDepartment())
                    .eq(CategoryMatch::getOthCategoryName, product.getCategory())
                    .eq(CategoryMatch::getOthCategoryType,product.getSubcategory())
                    .last("LIMIT 1")
            );
            Integer categoryId = null != categoryMatch ? categoryMatch.getCategoryId() : 1207;
            productRequest.setCateId(categoryId);
            productRequest.setCateIds(Arrays.asList(categoryId));

            productRequest.setImage(picList.get(0));
            if(gallery.size() > 0) {
                productRequest.setSliderImage(gallery.toJSONString());
            }
            productRequest.setIsShow(true);
            productRequest.setSpecType(true);
            productRequest.setIsEurope(ProductTypeEnum.LEAM.getCode());
            productRequest.setUnitName("件");
            productRequest.setLastPushTime(new Date());
            productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return productRequest;
    }

    /**
     * 
     * @author cyz
     * @date 2021/4/9 11:29
     * @param request
     * @param pageParamRequest 
     * @return com.common.CommonPage
     */
    @SuppressWarnings("rawtypes")
    @Override
    public CommonPage selectZoneProductList(ProductRequest request, PageParamRequest pageParamRequest) {
        if(request.getMerId() != 0){
            ChannelMerchant channelMerchant = channelMerchantService.getById(request.getMerId());
            List<String> brandIdsList= JSON.parseArray(channelMerchant.getBrandIds(), String.class);
            List<String> suppliersIdList = JSON.parseArray(channelMerchant.getSuppliersIds(), String.class);
            List<String> tempIdList = JSON.parseArray(channelMerchant.getTempId(), String.class);
            if (CollectionUtils.isNotEmpty(suppliersIdList)) {
                Supplier supplier = supplierService.getSupplierBarcode(request.getMerId());
                if (null != supplier) {
                    //商户如果是供应商的话 查询商户自建的商品 默认传入商户配置的供应商id
                    suppliersIdList.add(supplier.getId().toString());
                }
            }
            request.setBrandIdList(brandIdsList).setSuppliersIdList(suppliersIdList).setTempIdList(tempIdList);
            //查询商品上架数量
            request.setShowIds(Collections.singletonList(0));
            request.setTableNameMp(TableNameUtil.getProductMerName(request.getMerId()));
            List<Integer> cateIdList = categoryMatchService.selectCategoryMatchDisable(request.getMerId()).stream().map(CategoryMatch::getId).collect(Collectors.toList());
            request.setInvisibleCateIds(cateIdList);
        }else {
            request.setShowIds(null);
        }
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<StoreProduct> storeProductList = dao.selectZoneProductList(request);
        CommonPage<StoreProduct> storeProductCommonPage = CommonPage.restPage(storeProductList);
        if(CollectionUtils.isEmpty(storeProductList)){
            return CommonPage.restPage(new ArrayList<>());
        }
        // 匹配详情属性
        productConvertUtil.convertProduct(storeProductList);
        List<ProductResponse> productResponseArrayList = new ArrayList<>();
        //处理返回数据
        dealProductResponse(storeProductList, productResponseArrayList,request.getMerId());

        CommonPage<ProductResponse> productResponseCommonPage = CommonPage.restPage(productResponseArrayList);
        BeanUtils.copyProperties(storeProductCommonPage, productResponseCommonPage, "list");
        return productResponseCommonPage;
    }

    @Override
    public void saveProduct(StoreProductCrmebRequest storeProductCrmebRequest, StoreProduct storeProduct, Integer stock) {
        /****** 主表数据保存 *******/
        StoreProduct storeProductUpdate = new StoreProduct();
        BeanUtils.copyProperties(storeProductCrmebRequest, storeProductUpdate);
        storeProductUpdate.setStock(stock);

    	// 使用当前汇率
    	if(null == storeProductUpdate.getExchangeRate()) {
    		MoneyExchange moneyExchange = moneyExchangeService.getExchangeByName(Constants.EXCHANGE_EUR_NAME);
    		String eurRate = null == moneyExchange ? PriceUtil.DEFAULT_EXCHANGE_RATE_EUR : moneyExchange.getBankConversionPri();
    		storeProductUpdate.setExchangeRate(new BigDecimal(eurRate));
    	}
        storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                .eq(StoreProduct::getId, storeProduct.getId())
                .set(StoreProduct::getPrice, storeProductUpdate.getPrice())
                .set(null != storeProductUpdate.getPromotePrice(), StoreProduct::getPromotePrice, storeProductUpdate.getPromotePrice())
                .set(null != storeProductUpdate.getVipPrice(), StoreProduct::getVipPrice, storeProductUpdate.getVipPrice())
                .set(null != storeProductUpdate.getOtPrice(), StoreProduct::getOtPrice, storeProductUpdate.getOtPrice())
                .set(null != storeProductUpdate.getPostage(), StoreProduct::getPostage, storeProductUpdate.getPostage())
                .set(null != storeProductUpdate.getKeyword(), StoreProduct::getKeyword, storeProductUpdate.getKeyword())
                .set(null != storeProductUpdate.getBrandId(), StoreProduct::getBrandId, storeProductUpdate.getBrandId())
                .set(null != storeProductUpdate.getBrandName(), StoreProduct::getBrandName, storeProductUpdate.getBrandName())
                .set(null != storeProductUpdate.getGiveIntegral(), StoreProduct::getGiveIntegral, storeProductUpdate.getGiveIntegral())
                .set(null != storeProductUpdate.getCost(), StoreProduct::getCost, storeProductUpdate.getCost())
                .set(null != storeProductUpdate.getSourceCost(), StoreProduct::getSourceCost, storeProductUpdate.getSourceCost())
                .set(null != storeProductUpdate.getSpecType(), StoreProduct::getSpecType, storeProductUpdate.getSpecType())
                .set(null != storeProductUpdate.getCreateTime(), StoreProduct::getCreateTime, storeProductUpdate.getCreateTime())
                .set(null != storeProductUpdate.getLastPushTime(), StoreProduct::getLastPushTime, storeProductUpdate.getLastPushTime())
                .set(StoreProduct::getExchangeRate, storeProductUpdate.getExchangeRate())
                .set(StoreProduct::getIsShow, true)
                .set(StoreProduct::getStock, stock));
        Integer productId = storeProduct.getId();
        /****** attr表保存 ********/
        storeProductAttrService.removeByProductId(productId);
        List<StoreProductAttr> attrs = storeProductCrmebRequest.getAttr();
        attrs.forEach(e -> {
            e.setProductId(productId);
            e.setBarCode(storeProduct.getBarCode());
            e.setAttrValues(StringUtils.strip(e.getAttrValues().replace("\"", ""), "[]"));
        });
        storeProductAttrService.saveBatch(attrs);
        /****** value表保存 *********/
//        List<StoreProductAttrValue> dbStoreProductAttrValues = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery().eq(StoreProductAttrValue::getProductId, productId));
//        Map<String, StoreProductAttrValue> dbStoreProductAttrValueMap = dbStoreProductAttrValues.stream().collect(Collectors.toMap(StoreProductAttrValue::getSourceSkuId, s -> s, (value1, value2 )->{return value1;}));
        // 删除所有value
        storeProductAttrValueService.removeByProductId(productId);
        List<StoreProductAttrValueRequest> storeProductAttrValuesRequest = storeProductCrmebRequest.getAttrValue();
        List<StoreProductAttrValue> values = new ArrayList<>();
        for (StoreProductAttrValueRequest attrValuesRequest : storeProductAttrValuesRequest) {
            attrValuesRequest.setProductId(storeProduct.getId());
            attrValuesRequest.setBarCode(storeProduct.getBarCode());
            attrValuesRequest.setSourceSkuId(storeProductCrmebRequest.getIsEurope()+"-"+attrValuesRequest.getSourceSkuId());
            StoreProductAttrValue spav = new StoreProductAttrValue();
            BeanUtils.copyProperties(attrValuesRequest, spav);
            List<String> skuList = new ArrayList<>();
            for (Map.Entry<String, String> vo : attrValuesRequest.getAttrValue().entrySet()) {
                skuList.add(vo.getValue());
                spav.setSuk(String.join(",", skuList));
            }
            spav.setAttrValue(JSON.toJSONString(attrValuesRequest.getAttrValue()));
//            StoreProductAttrValue tempValue = dbStoreProductAttrValueMap.get(spav.getSourceSkuId());
//            if (null != tempValue) {
//                spav.setId(tempValue.getId());
//            }
            values.add(spav);
        }
        storeProductAttrValueService.saveBatch(values);
        /****** result表保存 ******/
        storeProductAttrResultService.remove(Wrappers.<StoreProductAttrResult>lambdaQuery().eq(StoreProductAttrResult::getProductId, productId));
        StoreProductAttrResult attrResult = new StoreProductAttrResult(/*0,*/ storeProduct.getId(), systemAttachmentService.clearPrefix(JSON.toJSONString(storeProductCrmebRequest.getAttrValue())), Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)), Constants.PRODUCT_TYPE_NORMAL, storeProduct.getBarCode());
        storeProductAttrResultService.save(attrResult);
        /****** Description表保存 ******/
        StoreProductDescription sd = storeProductDescriptionService.getOne(new LambdaQueryWrapper<StoreProductDescription>()
                .eq(StoreProductDescription::getProductId, productId)
                .last("LIMIT 1")
        );
        StoreProductDescription storeProductDescription = StoreProductDescription.getDescriptionByCrmeb(storeProductCrmebRequest);
        storeProductDescription.setId(ObjectUtil.isNotNull(sd) ? sd.getId() : null);
        storeProductDescription.setProductId(productId);
        storeProductDescriptionService.saveOrUpdate(storeProductDescription);

    }

    private StoreProductCrmebRequest buildEuropeProduct(EuropeProduct europeProduct) {
        List<EuropeProductSkuMerged> list = europeProduct.getSkuMergedList();
        // 规格处理
        StoreProductAttr storeProductAttr = new StoreProductAttr();
        storeProductAttr.setAttrName("尺寸");
        storeProductAttr.setType(0);
        StoreProductAttr storeProductAttrColor = new StoreProductAttr();
        storeProductAttrColor.setAttrName("颜色");
        storeProductAttrColor.setType(0);

        BigDecimal price = europeProduct.getPrice();
        BigDecimal referencePrice = europeProduct.getReferencePrice();
        List<StoreProductAttr> attrList = new ArrayList<StoreProductAttr>();
        List<StoreProductAttrValueRequest> attrValueList = new ArrayList<>();

        List<String> valueList = new ArrayList<>();
        List<String> valueColorList = new ArrayList<>();
        list.forEach(skuMerged -> {
            StoreProductAttrValueRequest storeProductAttrValueRequest = new StoreProductAttrValueRequest();
            storeProductAttrValueRequest.setImage(europeProduct.getGoodsImg());
            storeProductAttrValueRequest.setPrice(price);
            storeProductAttrValueRequest.setOtPrice(referencePrice);
            storeProductAttrValueRequest.setCost(price);
            storeProductAttrValueRequest.setStock(skuMerged.getStock());
            storeProductAttrValueRequest.setSourceSkuId(skuMerged.getSkuId());

            LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
            List<String> suk = new ArrayList<String>();
            if (StringUtils.isNotBlank(skuMerged.getColor())) {
                linkedMap.put("颜色", skuMerged.getColor());
                if (!valueColorList.contains(skuMerged.getColor())) {
                    valueColorList.add(skuMerged.getColor());
                }
                suk.add(skuMerged.getColor());
            }
            if (StringUtils.isNotBlank(skuMerged.getSize())) {
                linkedMap.put("尺寸", skuMerged.getSize());
                if (!valueList.contains(skuMerged.getSize())) {
                    valueList.add(skuMerged.getSize());
                }
                suk.add(skuMerged.getSize());
            }
            storeProductAttrValueRequest.setSuk(String.join(",", suk));
            storeProductAttrValueRequest.setAttrValue(linkedMap);
            attrValueList.add(storeProductAttrValueRequest);
        });
        if (CollectionUtils.isNotEmpty(valueColorList)) {
            storeProductAttrColor.setAttrValues(String.join(",", valueColorList));
            attrList.add(storeProductAttrColor);
        }
        if (CollectionUtils.isNotEmpty(valueList)) {
            storeProductAttr.setAttrValues(String.join(",", valueList));
            attrList.add(storeProductAttr);
        }

        StoreProductCrmebRequest productRequest = new StoreProductCrmebRequest();
        productRequest.setAttr(attrList);
        productRequest.setAttrValue(attrValueList);
        productRequest.setMerId(CrmebMerchantEnums.IM.getMerchantId());
        productRequest.setContent(europeProduct.getGoodsName());
        productRequest.setKeyword(europeProduct.getCode());
        List<EuropeProductSku> europeProductSku = europeProduct.getSkuList();
        productRequest.setStoreInfo(europeProductSku.get(0).getComposition());
        productRequest.setStoreName(europeProduct.getGoodsName());
        // 品牌对应
        StoreBrand buyerStoreBrand = storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                .eq(StoreBrand :: getOtherId, europeProduct.getBrandId())
                .eq(StoreBrand :: getType, 2)
                .eq(StoreBrand :: getStatus, true)
                .eq(StoreBrand :: getIsDeleted, false)
                .last("LIMIT 1")
                );
        StoreBrand storeBrand = null;
        if(null != buyerStoreBrand && null != buyerStoreBrand.getSuperId()) {
            storeBrand = storeBrandService.getById(buyerStoreBrand.getSuperId());
        }
        if (null != storeBrand) {
            productRequest.setBrandId(storeBrand.getId());
            productRequest.setBrandName(storeBrand.getEnName());
        }

        productRequest.setPrice(price);
        productRequest.setOtPrice(referencePrice);
        productRequest.setCost(price);

        CategoryMatch categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                .eq(CategoryMatch :: getType, CategoryTypeEnum.EUROPE)
                .eq(CategoryMatch :: getOthCategoryId, europeProduct.getCategoryId())
                .last("LIMIT 1")
                );
        Integer categoryId = null != categoryMatch ? categoryMatch.getCategoryId() : 0;
        productRequest.setCateId(categoryId);
        productRequest.setCateIds(Arrays.asList(categoryId));
        productRequest.setImage(europeProduct.getGoodsImg());
        productRequest.setBarCode(BarCodeEnum.EUROPE.getCode().toString() + europeProduct.getGoodId());
        // 商品图片
        if (StringUtils.isNotEmpty(europeProduct.getGallery())) {
            JSONArray arr = (JSONArray) JSONArray.parse(europeProduct.getGallery());
            List<String> sliderImages = new ArrayList<String>();
            if (!CollectionUtils.isEmpty(arr)) {
                arr.forEach(val -> {
                    JSONObject json = (JSONObject) val;
                    sliderImages.add(String.valueOf(json.get("img_original")));
                });
            }
            productRequest.setSliderImage(JSONObject.toJSONString(sliderImages));
        }
        productRequest.setIsShow(true);
        productRequest.setSpecType(true);
        // 发货地欧洲
        productRequest.setTempId(3);
        productRequest.setUnitName("件");
        // 是否服务商
        if (null != europeProduct.getSupplierId() && SuppliersIdEnum.EASY_FASHION.getCode().equals(europeProduct.getSupplierId() + "")) {
            productRequest.setMerUse(true);
        }
        productRequest.setSourceCost(price);

        //供应商
        Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
                .eq(Supplier :: getSuppliersName, "1MAG")
                .last("LIMIT 1")
                );
        if(null != supplier) {
            productRequest.setSuppliersId(supplier.getId());
            productRequest.setSuppliersName(supplier.getSuppliersName());
        }
        productRequest.setIsEurope(ProductTypeEnum.EUROPE.getCode());
        productRequest.setLastPushTime(new Date());
        return productRequest;
    }

    private StoreProductCrmebRequest buildImProduct(ImProductDTO imProductDTO, String rateFloat, String rate, String rateCost) {
        // 主商品对象
        StoreProductCrmebRequest productRequest = null;
        List<ImProductItemDTO> items = imProductDTO.getItems();
        try {
            ImProductItemDTO minSku = items.stream().min(Comparator.comparing(ImProductItemDTO :: getSalePrice)).get();
            // 成本价
            PriceResult priceResult = priceUtil.eur2Rmb(minSku.getSalePrice());
            BigDecimal erpPrice = priceResult.getPrice();
            // 市场价
            BigDecimal retailPrice = minSku.getRetailPrice();
            // 销售价(计算后)
            BigDecimal adjustPrice = PriceUtil.calePrice(new BigDecimal(rateFloat).multiply(erpPrice), rate);
            // 成本价(计算后)
            BigDecimal adjustCost = PriceUtil.calePrice(erpPrice, rateCost);
            // 品牌对应
            StoreBrand buyerStoreBrand = storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                    .eq(StoreBrand :: getOtherId, imProductDTO.getBrandId())
                    .eq(StoreBrand :: getType, 5)
                    .last("LIMIT 1")
                    );
            StoreBrand storeBrand = null;
            if(null != buyerStoreBrand) {
                if(null != buyerStoreBrand.getSuperId()) {
                    storeBrand = storeBrandService.getById(buyerStoreBrand.getSuperId());
                }
            }
            // 处理单独品牌价格(无法做成配置的)
            if(null != storeBrand && "13De Marzo".equals(storeBrand.getEnName())) {
                adjustPrice = PriceUtil.calePrice(retailPrice, "0.65");
            }
            
            /***** 处理对象构建 *******/
            List<StoreProductAttr> attrList = new ArrayList<StoreProductAttr>();
            List<StoreProductAttrValueRequest> attrValueList = new ArrayList<StoreProductAttrValueRequest>();
            for(ImProductItemDTO sku : items) {
                Integer productId = imProductDTO.getProductId();
                String barCode = BarCodeEnum.IM.getCode() + productId.toString();
                
                // 成本价
                BigDecimal erpSkuPrice = priceUtil.eur2Rmb(sku.getSalePrice()).getPrice();
                // 市场价
                BigDecimal retailSkuPrice = sku.getRetailPrice();
                // 销售价(计算后)
                BigDecimal adjustSkuPrice = PriceUtil.calePrice(new BigDecimal(rateFloat).multiply(erpSkuPrice), rate);
                // 成本价(计算后)
                BigDecimal adjustSkuCost = PriceUtil.calePrice(erpSkuPrice, rateCost);
                // 处理单独品牌价格(无法做成配置的)
                if(null != storeBrand && "13De Marzo".equals(storeBrand.getEnName())) {
                    adjustSkuPrice = PriceUtil.calePrice(retailSkuPrice, "0.65");
                }
                
                // value对象
                StoreProductAttrValueRequest storeProductAttrValue = new StoreProductAttrValueRequest();
                storeProductAttrValue.setProductId(productId);
                storeProductAttrValue.setSourceSkuId(sku.getItemId());
                storeProductAttrValue.setSuk(sku.getSize());
                storeProductAttrValue.setStock(sku.getQty());
                storeProductAttrValue.setPrice(adjustSkuPrice);
                storeProductAttrValue.setImage(JSON.toJSONString(imProductDTO.getImages()));
                storeProductAttrValue.setCost(adjustSkuCost);
                storeProductAttrValue.setSourceCost(erpSkuPrice);
                storeProductAttrValue.setBarCode(barCode);
                storeProductAttrValue.setOtPrice(retailSkuPrice);
                
                LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
                if (StringUtils.isNotBlank(sku.getSize())) {
                    linkedMap.put("尺寸", sku.getSize());
                }
                storeProductAttrValue.setAttrValue(linkedMap);
                attrValueList.add(storeProductAttrValue);

                // attr对象
                if(CollectionUtils.isEmpty(attrList)) {
                    StoreProductAttr attr = new StoreProductAttr();
                    attr.setProductId(productId);
                    attr.setAttrName("尺寸");
                    attr.setAttrValues(sku.getSize());
                    attr.setBarCode(barCode);
                    attrList.add(attr);
                } else {
                    StoreProductAttr attr = attrList.get(0);
                    attr.setAttrValues(attr.getAttrValues() + "," + sku.getSize());
                }
            }
            
            productRequest = new StoreProductCrmebRequest();
            productRequest.setExchangeRate(priceResult.getExchangeRate());
            productRequest.setAttr(attrList);
            productRequest.setAttrValue(attrValueList);
            // 强制写一个 商户id 作为buyer商品标识标识
            productRequest.setMerId(CrmebMerchantEnums.IM.getMerchantId());
            productRequest.setContent(imProductDTO.getDescription());
            productRequest.setKeyword(imProductDTO.getDesignerId());
            productRequest.setStoreInfo(imProductDTO.getDescription());
            productRequest.setStoreName(imProductDTO.getName());
            if(null != storeBrand) {
                productRequest.setBrandId(storeBrand.getId());
                productRequest.setBrandName(storeBrand.getEnName());
            }
            productRequest.setPrice(adjustPrice);
            productRequest.setOtPrice(retailPrice);
            productRequest.setCost(adjustCost);
            productRequest.setSourceCost(erpPrice);
            productRequest.setPromoteFlag(false);
            productRequest.setErpPromFlag(true);
            productRequest.setTempId(2);

            // 供应商
            Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
                    .eq(Supplier :: getSuppliersName, CrmebMerchantEnums.IM.getMerchantName())
                    .last("LIMIT 1")
                    );
            if(null != supplier) {
                productRequest.setSuppliersId(supplier.getId());
                productRequest.setSuppliersName(supplier.getSuppliersName());
            }
            // 分类
            CategoryMatch categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                    .eq(CategoryMatch :: getType, CategoryTypeEnum.IM)
                    .eq(CategoryMatch :: getOthCategoryId, imProductDTO.getCategoryId())
                    .last("LIMIT 1")
                    );
            Integer categoryId = null != categoryMatch ? categoryMatch.getCategoryId() : 0;
            productRequest.setCateId(categoryId);
            productRequest.setCateIds(Arrays.asList(categoryId));
            productRequest.setBarCode(BarCodeEnum.IM.getCode() + imProductDTO.getProductId().toString());
            List<String> gallery = imProductDTO.getImages();
            if(gallery.size() > 0) {
                productRequest.setImage(gallery.get(0).toString());
                productRequest.setSliderImage(JSON.toJSONString(gallery));
            }
            productRequest.setIsShow(true);
            productRequest.setSpecType(true);
            productRequest.setIsEurope(ProductTypeEnum.IM.getCode());
            productRequest.setUnitName("件");
            productRequest.setLastPushTime(new Date());
            productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return productRequest;
    }

    private StoreProductCrmebRequest buildImProductNew(ImProductInfoDTO imProductDTO,List<ImItemDTO> itemList) {
        // 主商品对象
        StoreProductCrmebRequest productRequest = null;
        try {
            ImItemDTO minSku = itemList.stream().min(Comparator.comparing(ImItemDTO :: getSalePrice)).get();
            // 成本价
            PriceResult priceResult = priceUtil.eur2Rmb(minSku.getSalePrice());
            BigDecimal erpPrice = priceResult.getPrice();
            // 市场价
            BigDecimal retailPrice = imProductDTO.getRetailPrice();
            // 品牌对应 (IM标准商品 type = 1)
            StoreBrand storeBrand = storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                    .eq(StoreBrand :: getId, imProductDTO.getBrandId())
                    .eq(StoreBrand :: getType, ProductTypeEnum.INSIDE)
                    .last("LIMIT 1")
            );
            // 5429 IM标准其他品牌
            if(null == storeBrand){
                storeBrand = storeBrandService.getById(5429);
            }
            /***** 处理对象构建 *******/
            String barCode = BarCodeEnum.IM.getCode() + imProductDTO.getProductId().toString();
            List<StoreProductAttr> attrList = new ArrayList<StoreProductAttr>();
            List<StoreProductAttrValueRequest> attrValueList = new ArrayList<StoreProductAttrValueRequest>();
            for(ImItemDTO sku : itemList) {
                // 成本价
                BigDecimal erpSkuPrice = priceUtil.eur2Rmb(sku.getSalePrice()).getPrice();
                // 市场价
//                BigDecimal retailSkuPrice = sku.getRetailPrice();

                // value对象
                StoreProductAttrValueRequest storeProductAttrValue = new StoreProductAttrValueRequest();
                storeProductAttrValue.setSourceSkuId(sku.getItemId());
                storeProductAttrValue.setSuk(sku.getSize());
                storeProductAttrValue.setStock(sku.getQty());
                storeProductAttrValue.setPrice(erpSkuPrice);
                if(imProductDTO.getImages().size() > 0) {
                    storeProductAttrValue.setImage(imProductDTO.getImages().get(0));
                }
                storeProductAttrValue.setCost(erpSkuPrice);
                storeProductAttrValue.setSourceCost(erpSkuPrice);
                storeProductAttrValue.setBarCode(barCode);
                storeProductAttrValue.setOtPrice(retailPrice);

                LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
                if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(sku.getSize())) {
                    linkedMap.put("尺寸", sku.getSize());
                }
                storeProductAttrValue.setAttrValue(linkedMap);
                attrValueList.add(storeProductAttrValue);
                // attr对象
                if(CollectionUtils.isEmpty(attrList)) {
                    StoreProductAttr attr = new StoreProductAttr();
                    attr.setProductId(imProductDTO.getProductId());
                    attr.setAttrName("尺寸");
                    attr.setAttrValues(sku.getSize());
                    attr.setBarCode(barCode);
                    attrList.add(attr);
                } else {
                    StoreProductAttr attr = attrList.get(0);
                    attr.setAttrValues(attr.getAttrValues() + "," + sku.getSize());
                }
            }

            productRequest = new StoreProductCrmebRequest();
            productRequest.setExchangeRate(priceResult.getExchangeRate());
            productRequest.setAttr(attrList);
            productRequest.setAttrValue(attrValueList);
            // 强制写一个 商户id 作为buyer商品标识标识
            productRequest.setMerId(CrmebMerchantEnums.IM.getMerchantId());
            productRequest.setContent(imProductDTO.getDescription());
            productRequest.setKeyword(imProductDTO.getDesignerId());
            productRequest.setStoreInfo(imProductDTO.getDescription());
            productRequest.setStoreName(imProductDTO.getName());
            if(null != storeBrand) {
                productRequest.setBrandId(storeBrand.getId());
                productRequest.setBrandName(storeBrand.getEnName());
            }
            productRequest.setPrice(erpPrice);
            productRequest.setOtPrice(retailPrice);
            productRequest.setCost(erpPrice);
            productRequest.setSourceCost(erpPrice);
            productRequest.setPromoteFlag(false);
            productRequest.setErpPromFlag(true);
            productRequest.setTempId(2);

            // 供应商
            Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
                    .eq(Supplier :: getSuppliersName, CrmebMerchantEnums.IM.getMerchantName())
                    .last("LIMIT 1")
            );
            if(null != supplier) {
                productRequest.setSuppliersId(supplier.getId());
                productRequest.setSuppliersName(supplier.getSuppliersName());
            }
            productRequest.setBarCode(barCode);
            // 分类 (IM type = 1)
            CategoryMatch categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                    .eq(CategoryMatch :: getType, CategoryTypeEnum.XUNWU)
                    .eq(CategoryMatch :: getId, imProductDTO.getCategoryId())
                    .last("LIMIT 1")
            );
            //1859 (IM标准 其他 其他)
            Integer categoryId = null != categoryMatch ? categoryMatch.getId() : 1859;
            productRequest.setCateId(categoryId);
            productRequest.setCateIds(Arrays.asList(categoryId));
            if(imProductDTO.getImages().size() > 0) {
                productRequest.setImage(imProductDTO.getImages().get(0));
                productRequest.setSliderImage(JSON.toJSONString(imProductDTO.getImages()));
            }
            productRequest.setIsShow(true);
            productRequest.setSpecType(true);
            productRequest.setIsEurope(ProductTypeEnum.IM.getCode());
            productRequest.setUnitName("件");
            productRequest.setComposition(imProductDTO.getComposition());
            productRequest.setDimension(imProductDTO.getDimension());
            productRequest.setColorCode(imProductDTO.getColorCode());
            productRequest.setSeasonCode(imProductDTO.getSeasonCode());
            productRequest.setLastPushTime(new Date());
            productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return productRequest;
    }

    /**
     * 商品下架
     * @Description:  
     * @author daigb 
     * @param @param id
     * @return void
     * @throws
     */
    private void soldOut(Integer id) {
        storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate().eq(StoreProduct::getId, id).set(StoreProduct::getIsShow, 0));
    }

    /**
     * 功能描述: 商品详情优惠券信息
     * @Param: [storeProducts, merId]
     * @Return: void
     * @Author: wangzh
     * @Date: 2023/4/28 11:11
     */
    private void getProductCoupons(List<ProductDetailResponse> storeProducts, Integer merId) {
        // 满足条件的优惠券
        List<StoreCoupon> storeCoupons = storeCouponService.list(Wrappers.<StoreCoupon>lambdaQuery()
                .eq(StoreCoupon::getStatus, 0)
                .ne(StoreCoupon::getLastTotal, 0)
                .le(StoreCoupon::getReceiveStartTime, new Date())
                .ge(StoreCoupon::getReceiveEndTime, new Date())
                .eq(StoreCoupon::getIsFixedTime, 0)
                .eq(StoreCoupon::getType, 1)
                .eq(StoreCoupon::getIsDel, 0)
                .eq(StoreCoupon::getMerId, merId));
        if (CollectionUtils.isEmpty(storeCoupons)) {
            return;
        }
        // 通过使用类型分类
        Map<Integer, List<StoreCoupon>> storeCouponsMap = storeCoupons.stream().collect(Collectors.groupingBy(StoreCoupon::getUseType));
        // 映射
        Map<Integer, StoreCoupon> storeCouponMap = storeCoupons.stream().collect(Collectors.toMap(StoreCoupon::getId, e -> e));
        Map<String, List<Integer>> storeProductCouponIdsMap = new HashMap<>();
        // 指定商品优惠券不为空
        if (Objects.nonNull(storeCouponsMap.get(2))) {
            List<StoreProductCoupon> storeProductCoupons = storeProductCouponService.list(Wrappers.<StoreProductCoupon>lambdaQuery().in(StoreProductCoupon::getIssueCouponId, storeCouponMap.keySet()));
            for (StoreProductCoupon storeProductCoupon : storeProductCoupons) {
                if (Objects.isNull(storeProductCouponIdsMap.get(storeProductCoupon.getProductId() + ""))) {
                    List<Integer> list = new ArrayList<>();
                    list.add(storeProductCoupon.getIssueCouponId());
                    storeProductCouponIdsMap.put(storeProductCoupon.getProductId() + "", list);
                } else {
                    storeProductCouponIdsMap.get(storeProductCoupon.getProductId() + "").add(storeProductCoupon.getIssueCouponId());
                }
            }

        }
        // 品类券不为空
        if (Objects.nonNull(storeCouponsMap.get(3))) {
            for (StoreCoupon storeCoupon : storeCouponsMap.get(3)) {
                if (Objects.isNull(storeProductCouponIdsMap.get(storeCoupon.getPrimaryKey()))) {
                    List<Integer> list = new ArrayList<>();
                    list.add(storeCoupon.getId());
                    storeProductCouponIdsMap.put(storeCoupon.getPrimaryKey(), list);
                } else {
                    storeProductCouponIdsMap.get(storeCoupon.getPrimaryKey()).add(storeCoupon.getId());
                }
            }
        }
        for (ProductDetailResponse productDetailResponse : storeProducts) {
            StoreProductStoreInfoResponse storeInfo = productDetailResponse.getStoreInfo();
            // 商品可用优惠券列表
            List<StoreCoupon> coupons = Optional.ofNullable(storeCouponsMap.get(1)).orElse(new ArrayList<>());
            // 指定商品
            if (Objects.nonNull(storeProductCouponIdsMap.get(storeInfo.getId() + ""))) {
                for (Integer id : storeProductCouponIdsMap.get(storeInfo.getId() + "")) {
                    coupons.add(storeCouponMap.get(id));
                }
            }
            JSONObject primaryKey = new JSONObject();
            JSONArray seasons = new JSONArray();
            seasons.add(storeInfo.getSeasonCode());
            JSONArray tempIds = new JSONArray();
            tempIds.add(storeInfo.getTempId());
            JSONArray brandIds = new JSONArray();
            brandIds.add(storeInfo.getBrandId());
            primaryKey.put("seasons", seasons);
            primaryKey.put("tempIds", tempIds);
            primaryKey.put("cateIds", storeInfo.getCateId());
            primaryKey.put("brandIds", brandIds);
            if (Objects.nonNull(storeProductCouponIdsMap.get(primaryKey.toJSONString()))) {
                for (Integer id : storeProductCouponIdsMap.get(primaryKey.toJSONString())) {
                    coupons.add(storeCouponMap.get(id));
                }
            }
            if (CollectionUtils.isNotEmpty(coupons)) {
                coupons = coupons.stream().sorted(Comparator.comparing(StoreCoupon::getMoney, Comparator.reverseOrder())).collect(Collectors.toList());
            }
            productDetailResponse.setStoreCoupons(coupons);
        }
    }

    /**
     * 商品列表 通过条形码
     * @author
     * @since 2023-06-01
     * @return CommonPage<ProductResponse>
     */
    @Override
    public CommonPage<ProductResponse> getListByBarcode(ProductRequest request, PageParamRequest pageParamRequest) throws Exception {
       String selfSourceSkuId =  request.getSelfSourceSkuId();
       Integer merId =  request.getMerId();

        //获取
        ChannelMerchant channelMerchant = channelMerchantService.getById(merId);

        if(null != channelMerchant) {

            //可见配置
            List<Integer> brandIdsList = JSON.parseArray(channelMerchant.getBrandIds(), Integer.class);
            List<Integer> suppliersIdList = JSON.parseArray(channelMerchant.getSuppliersIds(), Integer.class);
            List<Integer> tempIdList = JSON.parseArray(channelMerchant.getTempId(), Integer.class);

            //不可见分类
            List<Integer> cateIdList = categoryMatchService.selectCategoryMatchDisable(merId).stream().map(CategoryMatch::getId).collect(Collectors.toList());

            LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = Wrappers.<StoreProduct>lambdaQuery()
                    .eq(StoreProduct::getIsShow,1)
                    .gt(StoreProduct::getStock,0);

            if(CollectionUtils.isNotEmpty(brandIdsList)){
                lambdaQueryWrapper.in(StoreProduct::getBrandId,brandIdsList);
            }
            if(CollectionUtils.isNotEmpty(suppliersIdList)){
                lambdaQueryWrapper.in(StoreProduct::getSuppliersId,suppliersIdList);
            }
            if(CollectionUtils.isNotEmpty(tempIdList)){
                lambdaQueryWrapper.in(StoreProduct::getTempId,tempIdList);
            }
            if(CollectionUtils.isNotEmpty(cateIdList)){
                lambdaQueryWrapper.notIn(StoreProduct::getCateId,cateIdList);
            }

            lambdaQueryWrapper.notInSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(merId) + " WHERE is_not_show = 1");
            lambdaQueryWrapper.inSql(StoreProduct::getId,"SELECT product_id FROM eb_store_product_attr_value where stock > 0 and self_source_sku_id = '" + selfSourceSkuId + "'");

            // 结果查询
            List<StoreProduct> storeProductList = new ArrayList<>();

            PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
            storeProductList = dao.selectList(lambdaQueryWrapper);

            PageInfo<StoreProduct>  productPage = new PageInfo<StoreProduct>(storeProductList);

            storeProductList = productPage.getList();
            if (CollectionUtils.isEmpty(storeProductList)) {
                return CommonPage.restPage(new ArrayList<>());
            }

            // 匹配详情属性
            productConvertUtil.convertProduct(storeProductList);
            // 数据处理
            List<ProductResponse> productResponseArrayList = new ArrayList<>();
            dealProductResponse(storeProductList, productResponseArrayList, request.getMerId());

            CommonPage<ProductResponse> productResponseCommonPage = CommonPage.restPage(productResponseArrayList);
            productResponseCommonPage.setTotal(productPage.getTotal());
            productResponseCommonPage.setTotalPage(productPage.getPages());

            return productResponseCommonPage;

        }else
        {
            return CommonPage.restPage(new ArrayList<>());
        }

    }

}
